Welcome

首页 / 软件开发 / C++ / C++:接口继承(interface) 和 实现继承(implementation) 详解

C++:接口继承(interface) 和 实现继承(implementation) 详解2014-11-16继承接口和实现, 主要包含三种方式:

1. 只继承接口, 纯虚函数;

2. 继承接口和实现, 允许覆写(override), 虚函数;

3. 继承接口和实现, 不允许覆写(override), 非虚函数;

1. 纯虚函数:

只继承接口, 但是派生类必须实现其接口;

纯虚函数也可以包含实现, 但是只能在指明类(即, class::)的时候使用

2. 虚函数:

继承接口和实现, 派生类可以覆写(override), 也可以使用默认版本, 即基函数(base)版本;

纯虚函数约束程序更多, 虚函数更灵活;

3. 非虚函数

继承接口和实现, 强制的提供派生类的实现, 不可以改变, 即不可以覆写(override);

关于派生类使用纯虚函数的实现, 如下:

/************************************************* File: pure_virtual.cpp Copyright: C.L.Wang Author: C.L.Wang Date: 2014-04-01 Description: explicit Email: morndragon@126.com **************************************************//*eclipse cdt, gcc 4.8.1*/#include <iostream>using namespace std;class Shape {public:virtual void draw() const;virtual void error (const std::string& msg) {std::cout << msg << std::endl;};int objectID() const { return 1;};};void Shape::draw() const {std::cout << "Shape Draw!" << std::endl;}class Rectangle: public Shape {public:void draw() const {std::cout << "Rect Draw!" << std::endl;};};class Ellipse: public Shape {public:void draw() const {std::cout << "Elli Draw!" << std::endl;};};int main () {Shape* ps1 = new Rectangle;Shape* ps2 = new Ellipse;ps1->draw();ps2->draw();std::cout << "Attention: " << std::endl;ps1->Shape::draw();ps2->Shape::draw();return 0;}
输出:

Rect Draw!Elli Draw!Attention: Shape Draw!Shape Draw!
作者:csdn博客 Spike_King