C++ 虚拟函数不';不要进入基类

C++ 虚拟函数不';不要进入基类,c++,inheritance,virtual-functions,C++,Inheritance,Virtual Functions,我想知道为什么这个函数打印“aba h()”而不是“son h()”,因为它是虚拟的。我想这个函数可能隐藏了另一个函数,但它有相同的签名 class Aba: public Saba { public: Aba(){cout << "Aba Ctor" << endl;} Aba(const Aba& a){cout << "Aba Copy Ctor" << endl;} ~Aba(){cout <<

我想知道为什么这个函数打印“aba h()”而不是“son h()”,因为它是虚拟的。我想这个函数可能隐藏了另一个函数,但它有相同的签名

class Aba: public Saba {
public:
    Aba(){cout << "Aba Ctor" << endl;}
    Aba(const Aba& a){cout << "Aba Copy Ctor" << endl;}
    ~Aba(){cout << "Aba Dtor" << endl;}
    virtual void g(){cout << "Aba g()" << endl;}
    virtual void f(int){cout << "Aba f(int)" << endl;}
    virtual void h(){cout << "Aba h()" << endl;}
};

class Son: public Aba {

public:
    Son(){cout << "Son Ctor" << endl;}
    Son(const Son& a){cout << "Son Copy Ctor" << endl;}
    ~Son(){cout << "Son Dtor" << endl;}
    void f(){cout << "Son f()" << endl;}
    void h(){cout << "Son h()" << endl;}
};

virtual
方法基于所引用的对象类型进行解析。在您的情况下,对象类型始终为
Aba
,因为即使指定了
Son()
,对象也会被切片到
Aba
。因此,它打印
Aba::h()
方法

运行时动态绑定可以使用引用和指针。在以下情况下,它将打印
Son::h()


虚拟函数解析为对象的动态类型的对应函数,而不是静态类型,因为它与非虚拟函数相同:

Aba && one = Aba();
// static type: reference to Aba
// dynamic type of referenced object: Aba
因此,虚拟函数解析为定义为
Aba
成员的函数

Aba && two = Son();
// static type: reference to Aba
// dynamic type of referenced object: Son

现在一个虚拟函数将解析为
Son
中的定义,假设有这样的定义。

这里您使用一个静态对象调用函数
h
,因此该函数的调用仅在编译时得到解析,它与虚拟函数无关。此调用的绑定已完成。

只有在动态对象的情况下,绑定才会在运行时完成,查看指针指向的对象

Aba *ptr = new Son;
ptr->h(); //Ptr is pointing to Son, hence Son::h() will get called.

这是虚函数的明确目的。通过创建
Aba
h()
调用解析为
Aba::h
。虚拟函数知道创建的类型。非虚拟函数不是。为什么要打印
Son
任何内容?你根本不在
main()
中引用
Son
。@JohnKugelman只有在有ref的情况下你才能进入子的虚拟空间?我是说
Son
这个词根本不出现在
main()
中。只有
Aba
。所以当然,
Son
的代码都没有运行。@Barmar:它会调用Aba的复制构造函数,而a.h()仍然会打印相同的消息。要以多态方式调用方法,应该声明指针或引用类型。
Aba && two = Son();
// static type: reference to Aba
// dynamic type of referenced object: Son
Aba *ptr = new Son;
ptr->h(); //Ptr is pointing to Son, hence Son::h() will get called.