cpp中的接口 [英] Interface in cpp
问题描述
我想在cpp中创建接口,这样任何类实现该类,那么该类必须实现父类的功能。如果所有函数都没有实现则必须显示错误。
I want to create interface in cpp such that is any class implement that class then that class must implement parent class's functions. if all functions are not implemented then it must shows error.
class parent { // interface class
public :
virtual void display();
}
class base : public parent {
void display(); // this method must be implemented in this class
}
请帮我这个类继承在c ++中。
please help me for this type of inheritance in c++.
推荐答案
使用纯虚拟成员函数:
virtual void display() = 0;
这使得类抽象(你不能创建它的实例),以及任何非抽象类派生类必须实现这样的功能。
This makes the class abstract (you can't make instances of it), and any non-abstract deriving class must implement such functions.
这是一个维基百科链接,带有更正式的定义:
http://en.wikipedia.org/wiki/Virtual_function#Abstract_classes_and_pure_virtual_functions
Here's a Wikipedia link with a more formal definition: http://en.wikipedia.org/wiki/Virtual_function#Abstract_classes_and_pure_virtual_functions
这篇关于cpp中的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!