我试图了解复制赋值构造函数在 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;
}
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;};
};
测试.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
对象,但是使用这个构造函数就没有意义了,对吗?我要返回什么以及为什么?
我读过并发现返回参考文献是一个很好的做法,但我不知道应该如何做到这一点。
How
Add
return *this;
作为函数中的最后一行。
Test& Test::operator=(const Test& t) {
...
return *this;
}
Why
至于为什么要回国的问题*this
,答案是这是惯用的。
对于基本类型,您可以使用以下内容:
int i;
i = 10;
i = someFunction();
您可以在连锁操作中使用它们。
int j = i = someFunction();
您可以在条件中使用它们。
if ( (i = someFunction()) != 0 ) { /* Do something */ }
您可以在函数调用中使用它们。
foo((i = someFunction());
他们工作是因为i = ...
评估为参考i
。即使对于用户定义的类型,保留该语义也是惯用的。您应该能够使用:
Test a;
Test b;
b = a = someFunctionThatReturnsTest();
if ( (a = omeFunctionThatReturnsTest()).getAge() > 20 ) { /* Do something */ }
But Then
更重要的是,您应该避免为发布的类编写析构函数、复制构造函数和复制赋值运算符。编译器创建的实现足以满足Test
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)