Open licoded opened 1 year ago
&(a1=a2);
但为什么中间变量不能去取地址???
#include <iostream> class A{ public: int a; A() { std::cout << "empty ctor" << std::endl; } A(int a):a(a){ std::cout << "A(int a) ctor" << std::endl; } A(A &A_):a(A_.a){ std::cout << "A(A &A_) ctor" << std::endl; } // A& operator=(const A& other){ // correspond to results1 // a = other.a; // std::cout << "A& operator=(const A& other)" << std::endl; // return *this; // } A operator=(const A& other){ // correspond to results2 a = other.a; std::cout << "A operator=(const A& other)" << std::endl; return *this; } }; int main() { A a1(1), a2(2); std::cout << "====" << std::endl; a1 = a2; return 0; }
results1:
A(int a) ctor A(int a) ctor A(int a) ctor ==== A operator=(const A& other) A(A &A_) ctor
先赋值;赋值里面返回时,调了拷贝构造
results2:
A(int a) ctor A(int a) ctor A(int a) ctor ==== A& operator=(const A& other)
Point1: 两种形式不能同时写,是冲突的
Point2: 测试
&(a1=a2);
,返回值不加引用会报错Point3: 返回值不加引用就,多了一次拷贝
results1:
results2: