有这个代码:
#include <iostream>
class Base
{
public:
Base() {
std::cout << "Base: " << this << std::endl;
}
int x;
int y;
int z;
};
class Derived : Base
{
public:
Derived() {
std::cout << "Derived: " << this << std::endl;
}
void fun(){}
};
int main() {
Derived d;
return 0;
}
输出:
Base: 0xbfdb81d4
Derived: 0xbfdb81d4
但是,当 Derived 类中的函数 'fun' 更改为 virtual 时:
virtual void fun(){} // changed in Derived
那么'this'的地址在两个构造函数中都不相同:
Base: 0xbf93d6a4
Derived: 0xbf93d6a0
另一件事是如果类 Base 是多态的,例如我添加了一些其他虚函数:
virtual void funOther(){} // added to Base
然后两个“this”的地址再次匹配:
Base: 0xbfcceda0
Derived: 0xbfcceda0
问题是 - 当基类不是多态而派生类是多态时,为什么基类和派生类中的“这个”地址不同?