对于实现(编译器)不提供复制构造函数和复制赋值运算符的情况,我有一点困惑。
- 当我们在类中声明复制 ctor 和/或复制赋值运算符时。
- 有人说,当我们从具有私有复制 ctor 和/或复制赋值运算符的类派生时。
我对第二种情况有点迷茫,正是第二种情况。
a) 实现不会为您声明它们,因此您将收到编译时错误。
或者
b) 实现将声明和定义它们,但是当编译器定义的实现试图找到基类的方法时,我们会得到一个编译时错误。
我昨天接受了采访,我说它的(b)正在发生,但面试官不同意,他说它的(a)。
我尝试在 Microsoft C/C++ 14.00 和 gcc 4.4.5 中编译以下代码
struct A
{
private:
A& operator = ( const A& );
};
struct B : A
{
};
int main()
{
B b1;
B b2;
b1 = b2;
return 0;
}
微软编译器输出
ctor01.cpp(9) : error C2248: 'A::operator =' : cannot access private member declared in class 'A'
ctor01.cpp(4) : see declaration of 'A::operator ='
ctor01.cpp(2) : see declaration of 'A'
This diagnostic occurred in the compiler generated function 'B &B::operator =(const B &)'
gcc 编译器输出
Ctor01.cpp: In member function ‘B& B::operator=(const B&)’:
Ctor01.cpp:4: error: ‘A& A::operator=(const A&)’ is private
Ctor01.cpp:8: error: within this context
Ctor01.cpp: In function ‘int main()’:
Ctor01.cpp:15: note: synthesized method ‘B& B::operator=(const B&)’ first required here
所以我认为,实现会声明并定义它,但是当编译器定义的实现试图找到基类方法时,我们会得到一个编译时错误。如果我错了,请纠正我。