在派生类中声明的虚函数 [英] Virtual function declared in a derived class

查看:60
本文介绍了在派生类中声明的虚函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里我在 Derived 类中声明了另一个虚函数.

Here I have declared another virtual function in Derived class.

#include <iostream>

using namespace std;

class A{
    string s;
    public:
    A(const string& name) : s(name){}
     virtual void f1(){cout << "f1 of base class" << endl;};
};

class B : public A{
    string p;
    public:
    B(const string& name) : A(name){}
    virtual void f2(){cout << "virtual function of derived class" << endl;}
    void f1(){cout << "f1 of derived class";}
};

int main() {
    A* arr[] = {new A("John"),new B("Bob")};
    arr[0]->f1();
    arr[1]->f1();
    arr[1]->f2();
    return 0;
}

函数调用 arr[1]->f2() 给出错误'class A' has no member named 'f2'".我想知道为什么_vptr 指向基类的 VTABLE,即使 B 被向上转换为 A.

The function call arr[1]->f2() gives the error "‘class A’ has no member named ‘f2’".I am wondering why the _vptr points to the VTABLE of base class even when B is upcasted to A.

我也想知道,内联虚函数安全吗?

Also I wanted to know , is inlining virtual functions safe?

推荐答案

因为 is 没有这样的成员.virtual 函数从首先声明它们的类开始,一直到所有派生类.他们不会被冒泡.当编译器查看 arr[ i ]->f2() 时,它会查找 arr 的定义以了解其类型.arr 具有(静态)类型 A.因此,编译器查找 A 的定义以寻找 f2 的合适定义,但没有找到.因此诊断.

Because there is no such member. virtual functions take place from the class where they are declared first down through all derived classes. They do not get bubbled up. When the compiler looks at arr[ i ]->f2() it looks up the definition of arr for its type. arr has (static) type A. So, the compiler looks up A's definition for a suitable definition of f2 and doesn't find any. Hence the diagnostic.

virtual 函数可以安全地内联.事实上,所有的类内定义都是由编译器隐式内联的.所以,你的 A::f1 已经被内联了.

virtual functions can be safely inlined. In fact, all in-class definitions are implicitly inlined by the compiler. So, your A::f1 is already inlined.

这篇关于在派生类中声明的虚函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆