【面向对象程序设计常见面试题】派生中构造函数的几点说明(xx)

1、当基类构造函数不带参数时,派生类不一定需要定义构造函数;然而当基类的构造函数哪怕只带一个参数,它所

派生类都必须定义构造函数

2、基类使用默认的构造函数或不带参数的构造函数,则在派生类中定义构造函数时可忽略:“基类构造函数名(参

数)”

3、如果派生类的基类也是一个派生类,每个派生类只需要负责其直接基类数据成员的初始化


#include <iostream>
using namespace std;

class First
{
public:
    First(){
        a = 0;
        b = 0;
    }
    First(int x,int y){
        a = x;
        b = y;
    }
    void print(){
        cout<<"a="<<a<<" "<<"b="<<b<<endl;
    }
private:
    int a;
    int b;
};

class Second:public First
{
public:
    Second():First(1,1){
        c = 0;
        d = 0;
    }
   Second(int x,int y):First(x+1,y+1){
        c = x;
        d = y;
    }
    Second(int x,int y,int n,int m):First(x,y){
        c = n;
        d = m;
    }
    void print(){
        First::print();
        cout<<"c="<<c<<" "<<"d="<<d<<endl;
    }
private:
    int c;
    int d;
};


class Third:public Second
{
public:
    Third(){
        e = 0;
    }
    Third(int x,int y,int z):Second(x+1,y+1){
      e = z;
    }
    Third(int x,int y,int n,int m,int z):Second(x,y,m,n){
       e = z;
    }
    void print(){
        Second::print();
        cout<<"e="<<e<<endl;
    }
private:
    int e;

};

int main()
{
   First obj0;
   obj0.print();
   Second obj1;
   obj1.print();
   Third obj3;
   obj3.print();
   First obj4(10,10);
   obj4.print();
   Second obj5(10,10);
   obj5.print();
   Third obj6(20,20,10);
   obj6.print();
}


展开阅读全文
博主设置当前文章不允许评论。

没有更多推荐了,返回首页