为什么带有2个自变量参数的构造函数接受复制对象作为1个自变量参数?

时间:2018-06-19 13:10:46

标签: c++

redundacy

为什么带有2个自变量参数的构造函数接受复制对象作为参数。我们使用具有不同类型的1个自变量class person { std::string name; int age; public: person(const std::string& name, int age) : name(name), age(age) { } }; int main() { person a("Bjarne Stroustrup", 60); person b(a); // What happens here? b = a; // And here? } 调用构造函数,并且有效吗?

如何?

4 个答案:

答案 0 :(得分:3)

不是。这行代码:

person b(a);

调用隐式定义的person的{​​{3}}。由编译器生成的一个。如果您具有以下条件,它还将调用一个副本构造函数:

person b = a;

该构造函数接受类型为person&‍const person&‍volatile person&‍const volatile person&的一个参数。在您的情况下,这将是类型为a的对象person。它不会调用以下构造函数:

person(const std::string& name, int age)

答案 1 :(得分:2)

person b(a);

这将调用编译器为您生成的person的副本构造函数。编译器生成的版本看起来像这样(原始版本):

person(const person& other)
{
  name = other.name;
  age = other.age;
}

b = a;         // And here?

这将调用复制分配运算符,该运算符也是由编译器为您生成的,在这种情况下,它与复制构造函数大致相同。

答案 2 :(得分:1)

编译器通常会为您生成一些构造函数,包括person::person(const person &)使用的拷贝构造函数person b(a);和赋值运算符,包括person & person::operator=(const person &)使用的拷贝赋值运算符b = a;

答案 3 :(得分:0)

一个好的学习练习是,如果您不知道程序会自动执行什么操作,请自己实施该程序以了解其工作方式。 Here is a good website that explains the issue you have。关于构造函数在C ++中的工作方式

class person
{
    std::string name;
    int age;  
public:
    person(const std::string& name, int age) : name(name), age(age)
    {
    }
    /**
     * If you do nothing this is what is automaticaly impremented
     */
    personne(const person p)
    {
        this.name = p.name; // or p.getName()
        this.age = p.age; // or p.getAge()
    }

    person person::operator=(const person & p)
    {
        if(this == &p)
            return *this;
        this.name = p.name; // or p.getName()
        this.age = p.age; // or p.getAge()
        return *this;
    }

};

int main()
{
    person a("Bjarne Stroustrup", 60);
    person b(a);  // copy constructor
    b = a;        // assignment operator overloading 
}