简体   繁体   English

虚调用中的C++非虚函数调用

[英]C++ Non-virtual function call in a virtual call

Why is the output of this program "CLASS A"?为什么这个程序的输出是“CLASS A”? Isn't this determined to be of type B?难道不是确定为B型的? Doesn't it mean that this->g() should call the B class's version of g?不是说 this->g() 应该调用 B 类版本的 g 吗?

#include <iostream>

using namespace std;

class A {
private:
    void g() {
        cout << "CLASS A" << endl;
    }
public:
    virtual void f() {
        g();
    }
};

class B : public A {
public:
    void g() {
        cout << "CLASS B" << endl;
    }
};

int main() {
    A* a = new B();
    a->f();
}

Isn't this determined to be of type B?这不是确定为B型吗?

No. B may be the dynamic type, but the static type of *this is A within all its member functions.B可能是动态类型,但*this的静态类型在其所有成员函数中都是A

The member function g is not virtual, so therefore a call to it uses static binding.成员函数g不是虚拟的,因此对它的调用使用静态绑定。 In static binding, the dynamic type of the object is irrelevant - only the static type matters.在静态绑定中,对象的动态类型无关紧要——只有静态类型才重要。 A call to the non-virutal g within a member function of A should be a call to A::g .到非当前虚拟呼叫g的成员函数中A应该是一个呼叫A::g

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM