加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 为什么在构造期间在基类中调用重写的虚函数?

发布时间:2020-12-16 06:50:18 所属栏目:百科 来源:网络整理
导读:参见英文答案 C++ virtual function from constructor ????????????????????????????????????7个 有一个c程序: # include iostreamusing namespace std;class base{public: base() { cout"base"endl; f(); } virtual void f() { cout"base f"endl; }};class
参见英文答案 > C++ virtual function from constructor ????????????????????????????????????7个
有一个c程序:

# include <iostream>

using namespace std;

class base
{
public:
    base()
    {
        cout<<"base"<<endl;
        f();
    }
    virtual void f() {
        cout<<"base f"<<endl;
    }
};

class derive: public base
{
    public:
        derive()
        {
            cout<<"derive"<<endl;
            f();
        }
    void f() {
        cout<<"derive f"<<endl;
    }
};

int main()
{
    derive d;
    return 1;
}

它输出:

base
base f
derive
derive f

我想知道为什么基地出现?

我在基地的quessor扩展到:

cout<<"base"<<endl;
        this.f();

但这应该指出为什么基数f打印出来?

解决方法

在构造期间,在基类构造函数中,对象的实际类型是基础的,即使它继续成为派生的.在破坏期间也会发生同样的情况,顺便说一下,您还可以使用typeid验证类型.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读