为什么具有 2 个参数参数的构造函数接受复制对象作为 1 个参数参数?
Why constructor with 2 argument parameter accepts copy object as 1 argument parameter?
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
}
相关文章:
- 如何使用Visual Studio 2017在C++中为参数化对象数组使用唯一指针
- Arduino C++在构造函数中用参数声明对象数组
- 我使用向量来创建类对象列表.初始化向量时如何使用参数调用构造函数?
- 当指向对象的指针作为参数传递给 std::thread 时,内存可见性
- 如何在不使用指针的情况下将派生类的对象作为参数传递给基类中的函数?
- C++ 类对象作为函数参数
- 如何将对象数组作为参数传递给模板
- 使用向量初始化参数化构造函数的对象数组
- 如何将成员函数作为参数传递并在派生对象上执行方法列表
- 如何编写将展开以定义具有模板参数的对象的宏
- C++类对象 - 遍历基于参数的对象
- 将指针传递到成员的指针,从模板参数包到函数对象
- 如何将子类作为函数的参数传递给期望基类,然后将该对象传递到指向这些抽象类对象的指针向量中?
- 是否可以获取成员函数模板参数的拥有对象?
- C++多参数对象创建
- 在不创建参数对象的情况下解析constexpr函数
- 推断模板参数对象成员的类型
- 如何解析c++ v8中的参数对象
- 当默认参数对象被销毁时
- 为什么函数不能更改其参数对象的地址/引用值?