我有以下代码:
class Base {
public:
virtual Base& operator=(const Base& b);
};
class Derived : public Base {
virtual Derived& operator=(const Derived& d);
};
int main() {
Derived d1;
Derived d2;
Base *b1 = &d1;
Base *b2 = &d2;
*b1 = *b2; // <--
}
在标记的行中,为什么Base::operator=
调用函数而不调用派生函数?
我认为在运行时,编译器将评估*b1
并查看它是一个Derived
对象,然后评估*b2
也将其视为派生对象,然后调用派生对象。
编辑:
在评论之后,我想澄清为什么我没有为虚拟函数提供相同的签名:我对Base operator = function virtual进行设置的原因是告诉编译器在编译期间不要静态链接它,而是使用virtual运行时表。我还对派生的operator = function virtual进行了通知,以告诉编译器将其添加到虚拟表中并在完成所有静态链接后将其删除。
我不明白为什么在运行时将调用函数(* b2)的运算符评估为Base而不是派生
正确答案应归因于@imreal的注释(函数具有不同的原型)。
更改此:
virtual Derived& operator=(const Derived& d)
对此:
virtual Base& operator=(const Base& b)
当然,您可以在每个类中以不同的方式实现此功能...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句