c++ 子类调用父类有参构造函数

来源:互联网 发布:windows bash 编辑:程序博客网 时间:2024/06/03 11:15

(1)多态性

在C++或者Java中,多态性其中一个好处是减少代码量。子类越多,越明显。

(2)构造函数的调用

FatherClass  *pt = new ChildClass;

父类指针-->子类实例 , 首先调用父类构造函数,然后调用子类构造函数。

(3)如果子类构造函数无参数,一切都好办。但是,往往子类构造函数需要参数。那么应该怎么办呢?

可以这么写:子类构造函数名(子类总参数列表):父类构造函数名(参数列表)

(4)代码示例:

class Student {    public:        Student(char nam)        {            name = nam;        }        ~Student(){}    protected:        string name;    }class Student1:public Student{public :    Student1(string nam, int num):Student(nam)    {        age = num;    }    ~Student1(){}protected:    int age;}

(5)调用顺序

a.如果子类没有显示调用父类含参数的构造函数,那么在子类实例化过程中,

---顺序: 父类无参(默认)构造函数-->子类被调用的构造函数。

b.如果子类显示调用了父类的含参构造函数,那么在子类实例化过程中,

---顺序: 父类有参构造函数-->子类被调用的构造函数。


经典代码例子如下:

class A {public:    A() { printf("A(void) \n"); }    A(int d) { printf("A %d\n", d); }    ~A() { printf(" ~A \n"); }};class B : public A{public:    B(){        printf("B(void) \n");    }    B(int x) : A(x)    {        printf("B \n");    }    ~B() { printf("~B \n"); }};int main(int argc, char* argv[]){    B c;    B b(8); // 此处也自动调用了A的同签名的构造函数    printf("Hello World!\n");    getchar();    return 0;}


输出结果:



一句一句分析:

B  c;         

//首先调用A的无参(默认)构造函数,然后调用B的无参构造函数。

//所以先输出A(void),然后是B(void)


B  b(8);    

//首先调用A的有参构造函数,然后调用B的有参构造函数。

//所以先输出A 8,然后是B



如果,没有显示调用A的有参构造函数呢? 

答案是:不会调用A的有参构造函数,只会调用A的无参(默认)构造函数。如下图:






========================



0 0