问题
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
}
please help me for this type of inheritance in c++.
回答1:
Use a pure virtual member function:
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.
Here's a Wikipedia link with a more formal definition: http://en.wikipedia.org/wiki/Virtual_function#Abstract_classes_and_pure_virtual_functions
回答2:
Just one change
class parent { // interface class
public :
virtual void display() = 0;
}
This is called a pure virtual function in C++.
回答3:
you can use abstract class(or pure virtual class):
class AB {
public:
virtual void f() = 0;
};
abstract class can be used in cpp like interface in java/c#, although they were different in compiler's perspective.
来源:https://stackoverflow.com/questions/6974609/interface-in-cpp