当前位置: 代码迷 >> 综合 >> pure virtual function
  详细解决方案

pure virtual function

热度:18   发布时间:2023-11-16 23:28:23.0
#include <iostream>class Printable //先写一个可以打印,所有类名的interface(即是定义method为virtual function)
{
public:virtual std::string GetClassName() = 0;
};//定义一个基类,基类会打印自己的名字
class Entity : public Printable
{
public:virtual std::string Getname() { return "Entity"; }//实例化Printable的虚方法std::string GetClassName() { return "Class:Printable is printing the name of class : Entity"; }};//定义继承基类的子类,会打印自己的名字,并覆盖基类打印名字的method
class Player : public Entity
{
private:std::string _name;public:Player(const std::string& name): _name(name) {}std::string Getname() override { return _name; }//这是C11中引入的新特性,加入override可以使程序可读性更好。//还可以避免拼写错误,要是Getname()中有任何的拼写的问题,都会反映出来//实例化Printable的虚方法,不同的interface写不同的执行methodstd::string GetClassName() { return "Class:Printable is printing the name of class : Player!!!"; }
};//调用类中的print方法,传入函数的参数是基类指针(类的地址)
void PrintName(Entity* e)
{std::cout << e->Getname() << std::endl;
}//验证虚函数的method,打印各类的名称。
void Print(Printable* print)
{std::cout << print->GetClassName() << std::endl;
}int main(void)
{Entity* e = new Entity; //new申请的对象,则只有调用到delete时再会执行析构函数Print(e);//调用执行interface接口的类methodPlayer* p = new Player("Veyron!!!");Print(p);
}
  • 在C++中没有interface关键字(在java这样的语言中有的)
  • 这正是多态性的一种体现
  相关解决方案