考虑以下示例:
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()
?
答案 0 :(得分:0)
此处没有虚拟功能。因此,您可以从B1::f
致电B1::g
成员函数,按照定义 g
调用。如果f
是虚拟的,那么事情确实会有所不同,因为所有C::g
函数都会调用void g()
(只是尝试在所有3个结构中用virtual void g()
替换{{1}} )