c++ - 既然你可以在 C++ 中以两种方式声明一个复制构造函数,那哪种方式是正确的?

标签 c++ constructor copy-constructor

假设您有以下类(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/

相关文章:

c++ - QApplication构造函数段错误

c++ - 无法使用模板让此类工作吗?

c++ - 为什么这个 pop() 函数会产生段错误?

javascript - CategorySelect 不是构造函数

java - 代码调用 new GenericObject() 但 GenericObject.java 没有构造函数

java - 在 java 构造函数中声明 ArrayList

c++ - 没有调用模板类的复制构造函数

c++ - opencv 将网络摄像头输出写入 avi 文件

c++ - 为什么在分配发生时调用参数化构造函数?

c++ - 如何在创建复制构造函数时正确重载 operator=