C++赋值构造函数
C++ Assignment Constructor
如果我有两个类A和B,并且我做A=B,那么调用哪个赋值构造函数?A班的还是B班的?
有复制构造函数和赋值运算符。由于A != B
,将调用复制分配运算符。
简短回答:operator =
来自A级,因为你要分配给A级。
长答案:
A=B
将不起作用,因为A
和B
是类类型。
你的意思可能是:
A a;
B b;
a = b;
在这种情况下,将调用class A
的operator =
。
class A
{
/*...*/
A& operator = (const B& b);
};
对于以下情况,将调用转换构造函数:
B b;
A a(b);
//or
B b;
A a = b; //note that conversion constructor will be called here
其中A定义为:
class A
{
/*...*/
A(const B& b); //conversion constructor
};
请注意,这引入了B和A之间的隐式转换。如果不需要,可以将转换构造函数声明为explicit
class abc
{
public:
abc();
~abc();
abc& operator=(const abc& rhs)
{
if(&rhs == this) {
// do never forget this if clause
return *this;
}
// add copy code here
}
abc(const abc& rhs)
{
// add copy code here
}
};
Abc a, b;
a = b; // rhs = right hand side = b
因此,在左侧的对象上调用操作符。但请确保您不会错过if子句
相关文章:
- 为什么在使用转换构造函数赋值后调用C++类的析构函数?
- 为用户定义的类正确调用复制构造函数/赋值运算符
- C++:关于使用 Stroustrup 示例移动构造函数/赋值的问题
- 初始值设定项列表与构造函数赋值与变量定义
- std::vector::emplace() 真的在面对抛出移动构造函数/赋值运算符时提供了强大的异常保证吗?
- 创建一个类并在C++中使用构造函数(赋值)
- 如何为具有自引用指针的类实现复制构造函数/赋值运算符
- 使typedef的构造函数/赋值运算符成为友元函数
- 复制构造函数+赋值运算符
- C++ 矢量从构造函数赋值对象,无需临时
- 具有std::原子成员变量的类的复制构造函数/赋值运算符出错
- 初始化对象时复制构造函数/赋值运算符混淆
- 默认情况下是默认的构造函数/赋值noexcept/constexpr
- 模板是否应该为不同类型的参数制作非 Rvalue 引用构造函数/赋值
- 为什么 std 类型不提供来自分配器不同源的转换构造函数/赋值
- 是否为派生类生成的移动构造函数/赋值运算符
- 复制构造函数/赋值运算符
- C++复制构造函数/赋值运算符错误
- 正在获取要使用的移动构造函数/赋值运算符
- 影响正确性的move构造函数/赋值操作符示例