改为在C++中可以实现的
时间: 2025-02-02 13:11:53 浏览: 8
在C++中,多态性是一个非常重要的概念,主要通过虚函数和继承来实现。以下是C++中实现多态的几种方式:
虚函数(Virtual Functions): 虚函数是C++中实现运行时多态性的关键。通过在基类中将函数声明为虚函数,子类可以重写这些函数,从而实现不同的行为。
#include <iostream> using namespace std; class Base { public: virtual void show() { cout << "Base class show function" << endl; } }; class Derived : public Base { public: void show() override { cout << "Derived class show function" << endl; } }; int main() { Base* basePtr; Derived derivedObj; basePtr = &derivedObj; basePtr->show(); // 调用的是Derived类的show函数 return 0; }
纯虚函数和抽象类(Pure Virtual Functions and Abstract Classes): 纯虚函数是没有实现的虚函数,含有纯虚函数的类称为抽象类。抽象类不能被实例化,只能作为基类使用。
#include <iostream> using namespace std; class AbstractBase { public: virtual void show() = 0; // 纯虚函数 }; class Derived : public AbstractBase { public: void show() override { cout << "Derived class show function" << endl; } }; int main() { AbstractBase* basePtr; Derived derivedObj; basePtr = &derivedObj; basePtr->show(); // 调用的是Derived类的show函数 return 0; }
接口类(Interface Classes): 虽然C++没有像Java那样的接口关键字,但可以通过纯虚函数实现接口类。
#include <iostream> using namespace std; class Interface { public: virtual void show() = 0; virtual void display() = 0; }; class Implementation : public Interface { public: void show() override { cout << "Implementation of show function" << endl; } void display() override { cout << "Implementation of display function" << endl; } }; int main() { Interface* interfacePtr; Implementation implObj; interfacePtr = &implObj; interfacePtr->show(); // 调用的是Implementation类的show函数 interfacePtr->display(); // 调用的是Implementation类的display函数 return 0; }
通过以上方法,C++实现了多态性,使得代码更加灵活和可扩展。
相关推荐


















