Tôi đã cố gắng tìm rất nhiều rằng điều gì sẽ xảy ra nếu chỉ có một lớp được tạo ảo trong nhiều thừa kế? Hành vi của cuộc gọi hàm tạo không rõ ràng đối với tôi trong trường hợp này. Hãy nói ví dụ số-Trình tự các cuộc gọi hàm tạo trong nhiều thừa kế
#include<iostream>
using namespace std;
class grand{
public:
grand(){cout<<"grandfather"<<endl;}
};
class parent1:virtual public grand{ //virtual used only here
public:
parent1(){cout<<"parent1 "<<endl;}
};
class parent2: public grand{
public:
parent2(){cout<<"parent2"<<endl;}
};
class child:public parent1,public parent2{
public:
child(){cout<<"child"<<endl;}
};
int main() {
child s;
return 0;
}
Kết quả của đoạn mã này được đưa ra khi
grandfather
parent1
grandfather
parent2
child
nhưng trong đoạn code trên nếu chúng ta thay đổi này
class parent1:virtual public grand{
public:
parent1(){cout<<"parent1 "<<endl;}
};
class parent2: public grand{
public:
parent2(){cout<<"parent2"<<endl;}
};
này
class parent1:public grand{ //virtual removed from here
public:
parent1(){cout<<"parent1 "<<endl;}
};
class parent2:virtual public grand{ //virtual is added here
public:
parent2(){cout<<"parent2"<<endl;}
};
đầu ra được hiển thị là
grandfather
grandfather //why parent1 constructor is not called here?
parent1
parent2
child
Quan tâm của tôi là lý do tại sao hàm tạo parent1 không được gọi sau ông nội?
bản sao có thể có của [Thừa kế ảo, một lớp đủ?] (Http://stackoverflow.com/questions/13752482/virtual-inheritance-one-class-enough) – Mikhail
Không có điều này là về * thứ tự các cuộc gọi * không phải về * tự chia sẻ *. –