考虑以下示例:
struct B1 {
void f() {
this->g();
std::cout << this << std::endl;
}
void g() {
std::cout << "B1::g" << std::endl;
}
};
struct B2 {
void f() {
this->g();
std::cout << this << std::endl;
}
void g() {
std::cout << "B2::g" << std::endl;
}
};
struct C: B1, B2 {
void f() {
B1::f();
B2::f();
std::cout << this << std::endl;
}
void g() {
std::cout << "C::g" << std::endl;
}
};
int main() {
C c;
c.f();
return 0;
}
对我来说,输出是:
B1::g
0x7fffa11436b7
B2::g
0x7fffa11436b7
0x7fffa11436b7
让我们关注 B2::f
。从输出中可以看出,在 B2::f
内部,this
指向类型为 C
的对象的开头。那么,this->g()
是如何正确解析为 B2::g()
的呢?
最佳答案
这里没有虚函数。所以你从 B1::f
调用 g
成员函数,你调用 by definition B1::g
。如果 g
是虚拟的,事情确实会有所不同,因为所有 f
函数都会调用 C::g
(只是尝试替换 void g()
与 virtual void g()
在所有 3 个结构中)
关于c++ - 派生类的this指针是如何找到成员函数的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42325869/