我有一个简单的代码,它不能与引用(多态性)一起正常工作。
#include <iostream>
#include <string>
class Base {
public:
Base() {}
virtual ~Base() {}
virtual std::string text() const {
return "Base";
}
};
class Derived: public Base {
public:
Derived(Base& _b): b(_b) {}
virtual ~Derived() {}
virtual std::string text() const {
return b.text() + " - Derived";
}
private:
Base& b;
};
int main(int argc, char const *argv[])
{
Base b;
Derived d1(b);
std::cout << d1.text() << std::endl;
Derived d2(d1);
std::cout << d2.text() << std::endl;
return 0;
}
并输出:
Base - Derived
Base - Derived
我期望的输出中的第二行:Base - Derived - Derived
. 我阅读了一些资源,并且多态性与引用和指针完美配合,但在这种情况下,它没有。如果我用指针替换引用,它会再次工作。那么,任何人都可以给我一些解释吗?
非常感谢!