C++类之间的继承

一 被继承成员的访问权限

1 代码

#include <iostream>
using namespace std;
class CPolygon {
protected:
    int width, height;
public:
    void set_values(int a, int b) { width = a; height = b; }
};
    
class CRectangle : public CPolygon {
public:
    int area(void){ return (width * height); }
};
    
class CTriangle : public CPolygon {
public:
    int area(void){ return (width * height / 2); }
};
    
int main() {
    CRectangle rect;
    CTriangle trgl;
    rect.set_values(4, 5);
    trgl.set_values(4, 5);
    cout << rect.area() << endl;
    cout << trgl.area() << endl;
    return 0;
}

2 运行

[root@localhost test]# g++ test.cpp -g -o test
[root@localhost test]# ./test
20
10

3 说明

标识符protected与private类似,它们的唯一区别在继承时才表现出来。当定义一个子类型的时候,基类的protected成员可以被子类其他成员所使用,然而private成员就不可以。

二 基类继承的例子

1 代码

#include <iostream>
using namespace std;
class mother {
public:
    mother()
      { cout << "mother: no parameters\n"; }
    mother(int a)
      { cout << "mother: int parameter\n"; }
};
    
class daughter : public mother {
public:
    // 没有特别指定,调用基本默认构造函数
    daughter(int a)
      { cout << "daughter: int parameter\n\n"; }
};
    
class son : public mother {
public:
    // 调到指定的构造函数
    son(int a)
        : mother (a)
      { cout << "son: int parameter\n\n"; }
};
    
int main() {
    daughter cynthia(1);
    son daniel(1);
    return 0;
}

2 运行

[root@localhost test]# ./test
mother: no parameters
daughter: int parameter

mother: int parameter
son: int parameter

3 说明

基类的构造函数和析构函数没有被继承,但是当一个子类的object被生成或销毁的时候,其基类的默认构造函数(即没有任何参数的构造函数)和析构函数总是被自动调用的。

如果基类没有默认构造函数,或你希望当子类生成新的object时,基类的某个重载的构造函数被调用,需要在子类的每一个构造函数的定义中指定它。

三 多重继承的例子

1 代码

#include <iostream>
using namespace std;
class CPolygon {
protected:
    int width, height;
public:
    void set_values(int a, int b)
      { width = a; height = b; }
};
    
class COutput {
public:
    void output(int i);
};
    
void COutput::output(int i) {
    cout << i << endl;
}
    
class CRectangle : public CPolygon, public COutput {
public:
    int area(void)
      { return (width * height); }
};
    
class CTriangle : public CPolygon, public COutput {
public:
    int area(void)
      { return (width * height / 2); }
};
    
int main() {
    CRectangle rect;
    CTriangle trgl;
    rect.set_values(4, 5);
    trgl.set_values(4, 5);
    rect.output(rect.area());
    trgl.output(trgl.area());
    return 0;
}

2 运行

[root@localhost test]# g++ test.cpp -g -o test
[root@localhost test]# ./test
20
10

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值