假设您有以下类(class):
class Person{
string name;
int age;
int niNo;
public:
Person(const string & _name, const int & _age, const int & ni) : name(_name), age(_age), niNo(ni) {}
string getName() const{
return name;
}
int getAge() const{
return age;
}
int getNi() const{
return niNo;
}
bool operator==(const Person &p){
return name == p.getName() && age == p.getAge() && niNo == p.getNi();
}
然后你可以定义复制构造函数如下:
Person (const Person &other){
name = other.name;
age = other.age;
niNo = other.age;
}
或者像这样
Person (const Person &other) : name(other.getName()), age(other.getAge()), niNo(other.getNi()) {}
哪种方法最好?还是无所谓?
最佳答案
由于您的类可以简单地复制构造,因此最好的方法是在 C++11 中:
Person (const Person &other) = default;
否则,第二个更好,因为没有第一个中的默认 init 和 affection。
关于c++ - 既然你可以在 C++ 中以两种方式声明一个复制构造函数,那哪种方式是正确的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21282099/