标签:返回 font amp 结果 out 支持 operator c++ 不同
/******** 操作符重载 *** *** 下面三种方式,都支持连续加操作,但是稍有不同,你知道哪里不同吗 *** ******/ /** Test1 *****/ #if 0 class Calculate { int a; public: Calculate(void) : a(0) { cout << "Calculate(void)" << endl; } Calculate(int val) : a(0) { a = val; cout << "Calculate(int val) a = " << val << endl; } Calculate operator + (const Calculate& obj) { Calculate sum; // 无参构造 sum.a = this->a + obj.a; cout << "Calculate operator + (const Calculate& obj)" << endl; return sum; } int Getdata(void) { return a; } }; int main() { Calculate obj0(4); Calculate obj1(3); Calculate obj2(4); Calculate obj3; obj3 = obj1 + obj2; cout << "obj3.Getdata() = " << obj3.Getdata() << endl << endl; cout << "--分割线--下面是第二个打印块" << endl; obj3 = obj0 + obj1 + obj2; cout << "obj3.Getdata() = " << obj3.Getdata() << endl; while (1); return 0; } #endif /**** Test2 这个实验相比上面Test1,只改一处地方 ****/ /****** 请写出打印结果 *****/ #if 1 class Calculate { int a; public: Calculate(void) : a(0) { cout << "Calculate(void)" << endl; } Calculate(int val) : a(0) { a = val; cout << "Calculate(int val) a = " << val << endl; } Calculate operator + (const Calculate& obj) { Calculate sum; // 无参构造 sum.a = this->a + obj.a; cout << "Calculate operator + (const Calculate& obj)" << endl; return sum.a; /* 相比上面那个实验相,只改这里的返回值 */ } int Getdata(void) { return a; } }; int main() { Calculate obj0(4); Calculate obj1(3); Calculate obj2(4); Calculate obj3; obj3 = obj1 + obj2; cout << "obj3.Getdata() = " << obj3.Getdata() << endl << endl; cout << "--分割线--下面是第二个打印块" << endl; obj3 = obj0 + obj1 + obj2; cout << "obj3.Getdata() = " << obj3.Getdata() << endl; while (1); return 0; } #endif /** 实测结论: 第二个打印块内: Test2 会比Test1的多执行两个构造函数,即Calculate(int val)。 原因: Test2: obj3 = obj0 + obj1 + obj2 这句代码,先执行obj0 + obj1,会生成一个临时对象(假设称为X),其类型为返回值Calculate类型, 同时实际返回的是int类型,这就触发了只带一个int参数的构造函数的执行。 之后继续执行X + obj2 , 同理,会生成一个临时对象Y,先执行完Y的重载+的重载函数后,后调用Y的只带一个int参数的构造函数的执行,然后将Y赋值给obj3. **/ #if 0 /**** Test3 *****/ class Calculate { int a; public: Calculate(void) : a(0) { cout << "Calculate(void)" << endl; } Calculate(int val) : a(0) { a = val; cout << "Calculate(int val)" << endl; } Calculate operator + (const Calculate& obj) { cout << "obj.a = " << obj.a << endl; this->a += obj.a; cout << "Calculate operator + (const Calculate& obj)" << endl; return *this; } int Getdata(void) { return a; } }; int main() { Calculate obj0(4); Calculate obj1(3); Calculate obj2(4); Calculate obj3; obj3 = obj0 + obj1 + obj2; cout << "obj3.Getdata() = " << obj3.Getdata() << endl; while (1); return 0; } #endif
标签:返回 font amp 结果 out 支持 operator c++ 不同
原文地址:https://www.cnblogs.com/happybirthdaytoyou/p/13496428.html