在 C++ 中,如果我定义了一个复制构造函数和 operator=,它采用对该类的非 const 引用,编译器是否仍应为 const 引用提供默认版本?
struct Test {
Test(Test &rhs);
Test &operator=(Test &rhs);
private:
// Do I still need to declare these to avoid automatic definitions?
Test(const Test &rhs);
Test &operator=(const Test &rhs);
};
最佳答案
不,如果你定义一个复制构造函数和赋值运算符,编译器不会隐式声明或定义它自己的。请注意,复制构造函数 的定义允许参数由 const 或非 const 引用获取,因此您的构造函数确实是一个复制构造函数。 operator=
[省略了很大一部分细节,特别是在什么情况下隐式声明的特殊成员函数也会隐式定义]
12.8 [class.copy]/2 A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, and either there are no other parameters or else all other parameters have default arguments (8.3.6).
12.8 [class.copy]/7 If the class definition does not explicitly declare a copy constructor, one is declared implicitly.
12.8 [class.copy]/17 A user-declared copy assignment operator X::operator= is a non-static non-template member function of class X with exactly one parameter of type X, X&, const X&, volatile X& or const volatile X&.
12.8 [class.copy]/18 If the class definition does not explicitly declare a copy assignment operator, one is declared implicitly.
关于c++ - 如果我定义带有非常量参数的复制构造函数和 operator= ,我仍然会得到默认的复制构造函数和 operator= 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11936730/