我有以下类,我在类向量上重载+
运算符。
我也定义了自己的拷贝构造函数。这是代码::
class vector {
public:
int size;
vector() {
cout << "In empty constructor\n";
this->size = 5;
cout << "size = " << size << endl;
}
vector(int size) {
cout << "In size constructor\n";
this->size = size;
cout << "size = " << size << endl;
}
vector(const vector &v) {
cout << "inside copy constructor\n";
this->size = v.size;
cout << "size = " << this->size << endl;
}
vector operator ++() {
vector v = *this;
(this->size)++;
return v;
}
vector operator ++(int a) {
cout << "a = " << a << endl;
vector v = *this;
(this->size)++;
return v;
}
vector operator+(vector &a) {
vector v;
v.size = this->size + a.size;
return v;
}
vector& operator=(vector &a) {
cout << "Inside = assignment operator\n";
this->size = a.size;
return *this;
}
~vector() {
cout << "In destructor for vector of size = " << this->size << endl;
}
};
这是主要的::
int main(int argc, char** argv) {
vector v;
vector v2(27);
vector v3 = v + v2;
return 0;
}
我在构造函数中插入了cout
语句,以查看何时调用哪个构造函数。
根据我的理解,在我的行vector v3 = v + v2
中,应该调用复制构造函数,因为我们在调用期间初始化对象,因此在计算v + v2
复制构造函数之后应该被调用。但它并没有。我还尝试重载=
运算符以检查它是否正在分配值,但这也没有发生。
about程序的输出是这个::
In empty constructor
size = 5
In size constructor
size = 27
In empty constructor
size = 5
In destructor for vector of size = 32
In destructor for vector of size = 27
In destructor for vector of size = 5
在+
的重载函数中,我按值返回结果向量,所以我应该复制它。
为什么复制构造函数不会被调用?
感谢您提前提供任何帮助。
Ideone链接(如果有帮助):: http://ideone.com/S9EtjR