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

C中的虚函数

发布时间:2020-12-16 10:16:05 所属栏目:百科 来源:网络整理
导读:在我的C程序中: #includeiostream.hclass A{ public: virtual void func() { cout"In A"endl; }};class B:public A{ public: void func() { cout"In B"endl; }};class C:public B{ public: void func() { cout"In C"endl; }}; int main(){ B *ptr=new C; pt
在我的C程序中:

#include<iostream.h>

class A
{
    public:
    virtual void func()
    {
         cout<<"In A"<<endl;
    }
};

class B:public A
{
    public:
    void func()
    {
        cout<<"In B"<<endl;
    }
};

class C:public B
{
    public:
    void func()
    { 
        cout<<"In C"<<endl;
    }
};  

int main()
{
    B *ptr=new C;
    ptr->func();
}

该语句应该调用B :: func().但是,调用函数C :: func().请详细说明一下.一旦在’A类’中删除了虚拟关键字,就不会再发生这种情况了.

解决方法

有关基础知识,请阅读 C++ FAQ Lite on Virtual Functions.

A virtual function allows derived classes to replace the implementation provided by the base class. The compiler makes sure the replacement is always called whenever the object in question is actually of the derived class,even if the object is accessed by a base pointer rather than a derived pointer. This allows algorithms in the base class to be replaced in the derived class,even if users don’t know about the derived class.

(编辑:李大同)

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

    推荐文章
      热点阅读