一, 抽象类与接口
1, 抽象类简介
面向对象的抽象类用于表示现实世界的抽象概念, 是一种只能定义类型, 不能产生对象的类 (不能实例化), 只能被继承并被重写相关函数, 直接特征是相关函数没有完整实现.
C++ 语言没有抽象类的概念, 通过纯虚函数实现抽象类. 纯虚函数是指定义原型的成员函数, C++ 中类如果存在纯虚函数就成为了抽象类.
抽象类只能用作父类被继承, 子类必须实现父类纯虚函数的具体功能, 如果子类没实现纯虚函数, 子类也为抽象类.
抽象类不可以定义对象, 但是可以定义指针, 指针指向子类对象, 当子类中实现了纯虚函数, 可以实现多态.
- #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, 接口简介
C++ 中满足下列条件的类称为接口:
A, 类中没有定义任何的成员变量
B, 所有的成员函数都是公有的
C, 所有的成员函数都是纯虚函数
从以上条件可以知道, 接口是一种特殊的抽象类.
- #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;
- }
来源: http://www.bubuko.com/infodetail-2696124.html