C++ 继承

作者: 谢小帅 | 来源:发表于2017-05-13 23:56 被阅读72次

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

相关文章

网友评论

    本文标题:C++ 继承

    本文链接:https://www.haomeiwen.com/subject/gaffxxtx.html