C + + language learning (15)--c++ abstract class and interface one, abstract class and interface 1, abstract class introduction
Object-oriented abstract classes are used to represent the abstract concept of the real world, a class that can only define types, cannot produce objects (cannot be instantiated), can only be inherited and be overridden by related functions, and the direct feature is that the correlation function is not fully implemented.
The C + + language does not have the concept of abstract classes and implements abstract classes through pure virtual functions. A pure virtual function is a member function that defines a prototype, and a class in C + + becomes an abstract class if there is a pure virtual function.
Abstract classes can only be used as parent classes to be inherited, subclasses must implement the specific function of the parent class pure virtual function, if the subclass does not implement a pure virtual function, the subclass is also an abstract class.
An abstract class cannot define an object, but you can define a pointer that points to a subclass object that can be polymorphic when a pure virtual function is implemented in a subclass.
#include <iostream>using namespace std;class Shape{public: virtual double getArea()const = 0;};class Rectangle : public Shape{public: Rectangle(double a = 0, double b = 0) { m_width = a; m_height = b; } double getArea()const { return m_width * m_height; }private: double m_width; double m_height;};class Circle : public Shape{public: Circle(double radius = 0) { m_radius = radius; } double getArea()const { return 3.1415926*m_radius*m_radius; }private: double m_radius;};int main(int argc, char *argv[]){ Shape* shape; Rectangle rect(3,4); shape = ▭ cout << "Rectangle‘ area is " << shape->getArea() << endl; Circle circle(4); shape = &circle; cout << "Circle‘ area is " << shape->getArea() << endl; return 0;}
2. Introduction of interface
A class in C + + that meets the following conditions is called an interface:
A, no member variables are defined in the class
B, all the member functions are public
C, all member functions are pure virtual functions
From the above conditions can be known that the interface is a special kind of abstract class.
#include <iostream>using namespace std;class Channel{public: virtual bool open() = 0; virtual void close() = 0; virtual bool send(char* buf, int len) = 0; virtual int receive(char* buf, int len) = 0;};int main(int argc, char *argv[]){ Channel* channel; return 0;}
C + + language learning (15)--c++ abstract classes and interfaces