如何根据派生类的这个指针找到成员函数?

时间:2017-02-19 09:59:40

标签: c++ inheritance this static-typing

考虑以下示例:

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()

1 个答案:

答案 0 :(得分:0)

此处没有虚拟功能。因此,您可以从B1::f致电B1::g成员函数,按照定义 g调用。如果f是虚拟的,那么事情确实会有所不同,因为所有C::g函数都会调用void g()(只是尝试在所有3个结构中用virtual void g()替换{{1}} )