c++继承类构造函数

父类指针可以直接指向子类对象,父类引用可以直接引用子类对象,子类也可以看出父类对象,父子兼容性

#include <iostream> 
#include <string> 
using namespace std; 

class parent
{
protected :     
    char *name;
public:
    parent()
    {
        this->name="parent";
    }
    void print()
    {
        cout<<"name is:"<<name<<endl;
    }
};
class children: public parent
{
protected:
    int i;
public:
    children(int i)
    {
        this->name="child";
        this->i=i;
    }
};
int main()
{

     children c1(100);  

     parent p1=c1;    //直接赋值形式
     parent *p2=&c1; //父类指针指向子类对象
     parent &p3=c1;  //父类引用可以直接引用子类对象 

     p1.print();  //打印结果是name is:child
     p2->print();  //打印结果是name is:child
     p3.print();  //打印结果是name is:child

    getchar();
    return 0;
}



如何初始化父类成员?

先调用父类构造函数,再调用子类构造函数

继承与类组合混搭时如何初始化?

初始化顺序:口诀:先父母,后客人,再自己。

#include <iostream> 
#include <string> 
using namespace std; 
class object
{
public :
    object(const char*s)
    {
        cout<<"object:"<<s<<endl;
    }
};
class parent:public object
{
public:
    parent(const char*s):object(s)
    {
        cout<<"parent:"<<s<<endl;
    }

};
class children: public parent
{
protected:
    object o1;
    object o2;
public:
    children(const char* o1,const char* o2,const char* o3):o1(o1),o2(o2),parent(o3)
    {
        cout<<"chilren!"<<endl;
    }
};
int main()
{
    object o("i am object!");
    parent  p1("i am parent!");
    children c("o1","o2","parent from child!");


    getchar();
    return 0;
}



运行结果:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/shenlong1356/article/details/80993153