【发布时间】:2019-10-23 08:54:40
【问题描述】:
我试图了解复制赋值构造函数在 C++ 中的工作原理。我只使用过java,所以我真的不在我的水域。我已经阅读并看到返回参考是一个很好的做法,但我不明白我应该如何做到这一点。我写了这个小程序来测试这个概念:
main.cpp:
#include <iostream>
#include "test.h"
using namespace std;
int main() {
Test t1,t2;
t1.setAge(10);
t1.setId('a');
t2.setAge(20);
t2.setId('b');
cout << "T2 (before) : " << t2.getAge() << t2.getID() << "\n";
t2 = t1; // calls assignment operator, same as t2.operator=(t1)
cout << "T2 (assignment operator called) : " << t2.getAge() << t2.getID() << "\n";
Test t3 = t1; // copy constr, same as Test t3(t1)
cout << "T3 (copy constructor using T1) : " << t3.getAge() << t3.getID() << "\n";
return 1;
}
test.h:
class Test {
int age;
char id;
public:
Test(){};
Test(const Test& t); // copy
Test& operator=(const Test& obj); // copy assign
~Test();
void setAge(int a);
void setId(char i);
int getAge() const {return age;};
char getID() const {return id;};
};
test.cpp:
#include "test.h"
void Test::setAge(int a) {
age = a;
}
void Test::setId(char i) {
id = i;
}
Test::Test(const Test& t) {
age = t.getAge();
id = t.getID();
}
Test& Test::operator=(const Test& t) {
}
Test::~Test() {};
我似乎无法理解我应该在 operator=() 中放入什么。我见过人们返回*this,但我读到的只是对对象本身的引用(在= 的左侧),对吧?然后我考虑返回const Test& t 对象的副本,但是使用这个构造函数就没有意义了,对吧?我要返回什么,为什么?
【问题讨论】:
-
Test::operator=(const Test&)不是构造函数。它是一个复制赋值运算符。构造函数创建一个新对象;赋值运算符修改现有对象。 -
@SteliosPapamichail 看来你的老师对 C++ 概念不太熟悉。
-
旁注:通读Copy and Swap Idiom。它不仅是一个防弹(假设复制构造函数是正确的)赋值运算符,而且它很容易编写并且很难出错。它也有点重量级,所以它并不总是正确的解决方案,但它几乎总是一个很好的起点和停留,直到分析证明不是这样。
-
Test t3 = t1;和Test t3(t1);并不完全相同。例如,如果复制构造函数被标记为explicit,则只有第二个替代方案会编译。
标签: c++ copy-assignment