我试图了解复制赋值构造函数在 C++ 中是如何工作的。我只使用过java,所以我真的不在我的水域。我已经阅读并看到返回参考是一个很好的做法,但我不明白我应该如何做到这一点。我写了这个小程序来测试这个概念:
主.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;
}
测试.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;};
};
测试.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
对象的副本,但是使用这个构造函数没有意义吗?我要返回什么,为什么?