以下示例中会发生什么?
struct B { };
struct D1 : B { };
struct D2 : B { };
int main()
{
D1 d;
D2 d2;
B& x = d;
x = d2;
}
Run Code Online (Sandbox Code Playgroud)
我知道引用没有重新分配.x仍然指的是d,但是你怎么分配d2给d?
多一点:
struct B
{
B () { x = 0; }
int x;
virtual void foo () { cout << "B" << endl; }
};
struct D1 : B
{
D1 () { x = 1; }
virtual void foo () { cout << "D1" << endl; }
};
struct D2 : B
{
D2 () { x = 2; }
virtual void foo () { cout << "D2" << endl; }
};
int main()
{
D1 d;
D2 d2;
B& x = d;
x.foo(); //D1
//x.x is 1 here
x = d2;
x.foo(); //also D1
//but x.x is 2 here
}
Run Code Online (Sandbox Code Playgroud)
它似乎x.x更新了,但vftable不是......为什么?
| 归档时间: |
|
| 查看次数: |
1935 次 |
| 最近记录: |