gpt4 book ai didi

c++ - 构造函数的顺序 - 链式继承

转载 作者:太空狗 更新时间:2023-10-29 23:46:03 24 4
gpt4 key购买 nike

我运行下面的程序,在 main 的第一行之后我得到了这个输出:

1
6
1
6
13

谁能解释为什么它会两次进入GrandFather 的构造函数?

//base class 
class Grand{
public:
Grand(){cout<<"1"<<endl;}
Grand(const Grand & g){cout<<"2"<<endl;}
virtual ~Grand (){cout<<"3"<<endl;}
virtual void fun1(Grand g){cout<<"4"<<endl;}
virtual void fun3(){cout<<"5"<<endl;}
private:
int m_x;
};



//derived class
class Father: public Grand{
public:
Father(){cout<<"6"<<endl;}
Father(const Father & f){cout<<"7"<<endl;}
~Father(){cout<<"8"<<endl;}
void fun1(){cout<<"9"<<endl;}
void fun2(Father & f){
cout<<"10";
f.fun3();
}
void fun3(){
cout<<"11"<<endl;
}
virtual void fun4(){
cout<<"12"<<endl;
}
};


sing namespace std;

//derived class
class Son: public Father{
public:
Son(){cout<<"13"<<endl;}
Son(const Son& s){cout<<"14"<<endl;}
~Son(){cout<<"15"<<endl;}
void fun3(){cout<<"16"<<endl;}
virtual void fun5(Son& s){
cout<<"17"<<endl;
s.fun1();
}
private:
Father m_f;
};

int main(){
Grand * pGrand= new Son;
.........
.........
}

最佳答案

因为你既继承了 Father 又实例化了一个 Father 类型的成员,所以现在 Son 有两个 Father 对象——直接基类和一个成员。

关于c++ - 构造函数的顺序 - 链式继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14213085/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com