c – 为什么我不能拥有纯虚拟赋值运算符?
作者:互联网
我在C操作符中有点迷失.我想为两个不同的类强制执行赋值运算符,即因此可以为彼此分配一个:
class A {
public:
virtual A &operator =(const A &a) = 0;
};
class B : public A {
public:
virtual A &operator =(const A &a) override {
std::cout << "B" << std::endl;
return *this;
}
};
class C : public A {
public:
virtual A &operator =(const A &a) override {
std::cout << "C" << std::endl;
return *this;
}
};
int main(int argc, char *argv[])
{
B b;
C c;
b = c;
// leads to a linker error: undefined reference to `A::operator=(A const&)'
//B b2;
//b = b2;
}
第一项任务似乎完成了工作,“B”被称为.类似地,对于“c = b”,调用“C”.但是,当我取消注释第二部分时,我收到链接器错误.如果我定义A的运算符,如:
virtual A &operator =(const A &a) {
std::cout << "A" << std::endl;
return *this;
}
我得到“B”,“A”.咦?有人可以解释为什么在分配两个B时需要“A”而在B < - C时不是吗?
解决方法:
编译器生成一个隐式复制赋值运算符,当您执行B = B赋值时,该运算符被选中.执行B = C分配时,不会选择此选项.
http://en.cppreference.com/w/cpp/language/copy_assignment
https://wandbox.org/permlink/CM5tQU656rnwtrKl
如果您查看错误消息:
/tmp/cctHhd0D.o: In function `B::operator=(B const&)':
prog.cc:(.text._ZN1BaSERKS_[_ZN1BaSERKS_]+0x1f): undefined reference to `A::operator=(A const&)'
collect2: error: ld returned 1 exit status
您可以看到链接器错误来自B :: operator =(B const&)内部,因为您没有定义,所以它必须是自动生成的.
标签:c,operator-overloading,assignment-operator 来源: https://codeday.me/bug/20190828/1751515.html