C++类之间的继承

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chengqiuming/article/details/88622525

一 被继承成员的访问权限

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

猜你喜欢

转载自blog.csdn.net/chengqiuming/article/details/88622525
今日推荐