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

Why constructor with 2 argument parameter accepts copy object as 1 argument parameter?

本文关键字:参数 对象 复制 构造函数 为什么      更新时间:2023-10-16
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?
}

为什么带有 2 个参数参数的构造函数接受复制对象作为参数。我们用 1 个参数调用构造函数person b(a)不同类型的构造函数,它有效吗?

如何?

它没有。这行代码:

person b(a);

调用隐式定义person的复制构造函数。由编译器生成的一个。如果您有以下情况,它还将调用复制构造函数:

person b = a;

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

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

这将调用编译器为您生成的person的复制构造函数。编译器生成的版本看起来有点像这样(朴素版本(:

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

b = a;         // And here?

这将调用复制赋值运算符,该运算符也是由编译器为您生成的,在这种情况下,该运算符或多或少与复制构造函数相同。

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

一个好的学习练习是,如果你不知道你的程序自动做了什么,自己实现它以了解事情是如何工作的。这是一个很好的网站,可以解释您遇到的问题。这是关于构造函数在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 
}