<分区>
我有以下 C++ 代码:
#include <iostream>
class Base {
public:
Base() { }
Base(const Base& other) { this->foo(); }
virtual ~Base() { }
virtual void foo() { std::cout << "Base::foo" << std::endl; }
};
class My : public Base {
public:
My() : Base() { }
My(const My& other) : Base(other) { }
virtual ~My() { }
void foo() { std::cout << "My::foo" << std::endl; }
};
int main(int argc, char** argv);
int main(int argc, char** argv) {
My* my = new My();
My* my2 = new My(*my);
}
类 My
继承自 Base
。重要的是 Base
有一个虚方法 foo
,它在 My
中被覆盖。
多态性没有发挥作用
在 Base
的复制函数中,由 My
的复制函数调用,我调用 foo
。但是我希望 Base::Base(const Base&)
调用 My::foo
,但是在运行程序时我得到:
Base::foo
为什么会这样?多态性应该调用 My::foo
吗?