6

我在使用引用变量时发现了一个奇怪的行为。

这是类实现:

class Base {
    public:
        virtual void Method() = 0;
};

class DerivedA : public Base {
    public:
        virtual void Method() {}
}

class DerivedB : public Base {
    public:
        virtual void Method() {}
}

这是一个具有奇怪行为的示例代码:

void main(int argc, char *argv[]) {
    DerivedA a;
    DerivedB b;
    Base &base = a;

    base.Method();   // Calls DerivedA::Method

    base = b;
    base.Method();   // Calls DerivedA::Method!!! Why doesn't call DerivedB.Method()?
}

总之,似乎只有在初始化引用变量时才确定与引用变量“关联”的虚函数指针表。如果我重新分配参考变量,vfpt不会改变。

这里会发生什么?

4

2 回答 2

13

Base &base是一个引用,即a对象的别名,所以赋值base = b等价于a = b,这使得basethingie 仍然是同一个类的同一个对象。正如您似乎假设的那样,这不是指针的重新分配。

于 2011-12-03T10:42:23.070 回答
7

引用只能初始化一次。您不能将新对象分配给引用。这里实际发生的是 Base 的 operator= 被调用,而底层对象仍然是 DerivedA 而不是 DerivedB。

于 2011-12-03T10:43:55.307 回答