拓冰建站拓冰建站
首页 / 资讯中心 / 正文

理解拷贝赋值运算符(copy‑assignment operator)b.operator=(a)

Person a,b;b a; //b a;即b.operator(a)理解拷贝赋值运算符copy‑assignment operatorPersonPerson::operator(constPersonother){if(thisother){return*this;}nameother.getName();coutthis: thisendl;return*this;}结合下述代码对拷贝赋值运算符函数进行解读。Person a,b;b a;//b a; 即b.operator(a)各个变量分别对应谁this → 就是 bb 调用 operator成员函数内部 this 指针指向左边对象 b。other 形参 → 是 a 的引用const Person other aother 就是 a代表右边源对象 a。if(this other)判断 b a也就是自己赋值给自己 b b;直接返回。name other.getName();this-name a.getName()也就是修改 b 内部的成员变量把 a 的数据拷贝到 b 身上。返回值 Person return *this;this 是指针 Person**this对指针解引用得到对象本身b返回类型 Person返回b 的引用不是拷贝新对象。扩展return *this 不是把值再赋值给谁 b a; 这个语句的赋值动作在函数体内就已经做完了nameother.getName()已经修改 b。返回引用是为了支持链式写法Person c;c b a; // 等价 c (b a);先执行 b a函数返回 b的引用再拿这个返回的引用去执行 c b。如果不返回引用链式赋值就写不了。拆解链式 c b a;// b a执行operator返回 Person 也就是 bc (b.operator(a));代码调用函数this 指向other 引用作用b a;operator(a)b左边已有对象a修改已存在的 bPerson b(a);拷贝构造b刚创建的新 ba新建 b
分享:

看完干货,该让你的企业上线了

免费需求沟通 · 48 小时内出具建站方案 · 河南本地可上门