C++ 类的赋值运算时,构造函数的调用

时间:2024-12-05 19:27:44
#include <iostream> using namespace std; class Box { int length; std::string name = "box_default"; public: Box(std::string s) { name = s; std::cout << "Default constructor: "<< name << std::endl; } Box(const Box& b) { std::cout << "Copy constructor: "<< b.name << ", length: " << b.length << std::endl; std::cout << "Copy constructor : this : " << this->name << std::endl; this->length = b.length; this->name = "box_copy"; std::cout << "Copy constructor end: this : " << this->name << ", b : " << b.name << std::endl; } int getLength(void) { return length; } void setLength(int len) { length = len; } // 重载 + 运算符,用于把两个 Box 对象相加 Box operator+(const Box& b) { Box box("box+"); box.length = this->length + b.length; std::cout << "operator+: this: " << this->name << " ,b: " << b.name << std::endl; return box; } Box& operator = (const Box& b) { std::cout << "operator=: this: " << this->name << ", b: " << b.name << std::endl; std::cout << "length: " << b.length << std::endl; this->name = b.name; this->length = b.length; return *this; } }; // 程序的主函数 int main() { Box Box1("box1"); // 声明 Box1,类型为 Box Box Box2("box2"); // 声明 Box2,类型为 Box Box Box3("box3"); // 声明 Box3,类型为 Box // Box1 详述 Box1.setLength(6); // Box2 详述 Box2.setLength(12); // Box1 cout << "Length of Box1 : " << Box1.getLength() << endl; // Box2 cout << "Length of Box2 : " << Box2.getLength() << endl; // 把两个对象相加,得到 Box3 Box3 = Box1 + Box2; // Box3 cout << "Length of Box3 : " << Box3.getLength() << endl; return 0; }

相关文章