C++ 继承

C++ 继承

  • 派生类在继承时默认的访问修饰符为 private,一般都会使用 public,这样才能继承基类 public 和 protected 型的成员变量和函数
  • 派生类可以访问基类中所有的非私有成员。因此基类成员如果不想被派生类的成员函数访问,则应在基类中声明为 private

继承类型

  • 公有继承(public):当一个类派生自公有基类时,基类的公有成员也是派生类的公有成员,基类的保护成员也是派生类的保护成员,基类的私有成员不能直接被派生类访问,但是可以通过调用基类的公有和保护成员来访问
  • 保护继承(protected): 当一个类派生自保护基类时,基类的公有和保护成员将成为派生类的保护成员
  • 私有继承(private):当一个类派生自私有基类时,基类的公有和保护成员将成为派生类的私有成员
#include <iostream>

using namespace std;

// 基类
class Shape {
public:
    void setWidth(int w) {
        width = w;
    }

    void setHeight(int h) {
        height = h;
    }

protected:
    int width;
    int height;
private:
    void show() {
        cout << "私有方法" << endl;
    }
};

// 派生类 access specifier: public
// 才能继承基类公有的成员变量和函数
class Rectangle : public Shape {
public:
    int getArea() {
        return (width * height);
    }
};

int main() {
    Rectangle rect;
    rect.setWidth(5);
    rect.setHeight(7);
    cout << "Total area: " << rect.getArea() << endl; // 输出对象的面积
    return 0;
}
Total area: 35

多继承

  • C++多继承,Java单继承,多接口
#include <iostream>

using namespace std;

// 基类 Shape
class Shape {
public:
    void setWidth(int w) {
        width = w;
    }

    void setHeight(int h) {
        height = h;
    }

protected:
    int width;
    int height;
};

// 基类 PaintCost
class PaintCost {
public:
    int getCost(int area) {
        return area * 70;
    }
};

// 派生类,继承了2个基类的方法
class Rectangle : public Shape, public PaintCost {
public:
    int getArea() {
        return (width * height);
    }
};

int main(void) {
    Rectangle Rect;
    Rect.setWidth(5);
    Rect.setHeight(7);
    int area = Rect.getArea();
    cout << "Total area: " << area << endl; // 输出对象的面积
    cout << "Total paint cost: $" << Rect.getCost(area) << endl; // 输出总花费
    return 0;
}
Total area: 35
Total paint cost: $2450
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android NDK开发之旅 目录 C++ 继承 面向对象程序设计中最重要的一个概念是继承。继承允许我们依据另一...
    香沙小熊阅读 1,171评论 0 0
  • 概念及工方式 保持已有类的特性而构造新类的过程称为继承。在已有类的基础上新增自己的特性而产生新类的过程称为派生。被...
    帅碧阅读 451评论 1 1
  • 面向对象程序设计中最重要的一个概念是继承。继承允许我们依据另一个类来定义一个类,这使得创建和维护一个应用程序变得更...
    资深小夏阅读 160评论 0 0
  • C++文件 例:从文件income. in中读入收入直到文件结束,并将收入和税金输出到文件tax. out。 检查...
    SeanC52111阅读 2,855评论 0 3
  • 类成员的访问权限 继承方式 派生类的成员(及友元)对基类成员的访问权限只与基类中的访问说明符有关。派生列表中访问说...
    安然_fc00阅读 1,145评论 0 1