【发布时间】:2019-10-11 07:56:22
【问题描述】:
我关心的是运行时多态性。我非常理解使用基类指针和“虚拟”关键字来实现它的概念。而且我确实理解为什么编译器将调用解析推迟到运行时。但是,我很困惑为什么编译器会在使用引用而不是指针时推迟它。引用一旦被分配,就不能引用其他任何东西。那么,编译器不是已经知道引用指的是什么对象了吗?那么,当有基类引用而不是指针时,为什么它不静态解析函数调用呢? 这与指针不同,因为它可以在运行时指向类层次结构中的任何对象。但是参考是固定的!
这是一个代码sn-p:
class Base
{
protected:
int m_value;
public:
Base(int value)
: m_value(value)
{
}
virtual const char* getName() const { return "Base"; }
int getValue() const { return m_value; }
};
class Derived: public Base
{
public:
Derived(int value)
: Base(value)
{
}
virtual const char* getName() const { return "Derived"; }
};
int main()
{
Derived derived(5);
std::cout << "derived is a " << derived.getName() << " and has value " <<
derived.getValue() << '\n';
Base &ref = derived;
std::cout << "ref is a " << ref.getName() << " and has value " << ref.getValue() << '\n';
Base *ptr = &derived;
std::cout << "ptr is a " << ptr->getName() << " and has value " << ptr- >getValue() << '\n';
return 0;
}
【问题讨论】:
标签: c++11 reference polymorphism runtime virtual