C++ 之虚函数

温故知新,现在终于能明白C++的虚函数怎么回事了。在C++的道路上也越来越接近主干道了。

用代码最能说明

#include <iostream>

class sharp {
public:
    virtual void display()=0;
};

class sharp1 : public sharp{
public:
    virtual void display(){ std::cout<<"sharp1\n";}
};

class sharp2 :public sharp{
public:
    virtual void display(){ std::cout<<"sharp2\n";}
};

void main(){

sharp1 s1;
sharp2 s2;

sharp * psharp[2]={&s1,&s2};

for (int i=0;i!=2;++i){
    psharp[i]->display();
}
}

运行结果:

cpp_virtual

关键字:C++, 继承, 虚函数, 多态, 动态绑定

Leave a Reply

Your email address will not be published. Required fields are marked *