考虑下面的例子:
#include <iostream> using std::cout; using std::endl; class CBox { public: CBox(double lv = 1.0,double wv = 1.0,double hv = 1.0) : m_Length {lv},m_Width {wv},m_Height {hv} { cout << "Constructor called" << endl; } //CBox& operator=(double) //{ // cout << "Assignment operator called" << endl; // return *this; //} double volume() const { return m_Length* m_Width* m_Height; } private: double m_Length; double m_Width; double m_Height; }; int main() { CBox Box {1.0,1.0,1.0}; // no need for intializer list,but put it anyway Box = 2.0; // why is this calling constructor again ?! cout << Box.volume() << endl; // prints 2 }
请注意,我有意地注释掉了重载的赋值运算符.
执行此程序会产生以下输出:
Constructor called Constructor called 2
我注意到,即使Box对象已被初始化,下一个语句也是故意地调用构造函数.这是什么意思?
我知道这可以通过explicit关键字来防止,所以构造函数将是:
explicit CBox(double lv = 1.0,m_Height {hv} { cout << "Constructor called" << endl; }
但我宁愿期望影响如下结构:
CBox Box = 2.0;
当然,当我取消注释重载的赋值运算符时,它优先于构造函数.