类A,B1,B2,C在同一个cpp里写(Class.cpp)。分开麻烦的写一个里面省事。
上代码:
#include<iostream> #include<string>
class A { public: std::string firstName; public: A() { firstName = "NO FIRST NAME"; } A(std::string S) { firstName = S; } void OutName() { std::cout << "firstName: " << firstName << std::endl; } };
class B1 :virtual public A { public: std::string secondName; public: B1(std::string first, std::string second) :A(first), secondName(second) { } B1(std::string second) { secondName = second; firstName = "3"; } B1() { secondName = "NO SECOND NAME"; firstName = "NO FIRST NAME"; } void OutName() { std::cout << "first name:" << firstName << " second name:" << secondName << std::endl; } }; class B2 :virtual public A { public: std::string secondName2; public: B2(std::string first, std::string second) :A(first), secondName2(second) { } B2(std::string second) { secondName2 = second; firstName = "1"; } B2() { secondName2 = "NO SECOND NAME"; firstName = "NO FIRST NAME"; } void OutName() { std::cout << "first name:" << firstName << " second name:" << secondName2 << std::endl; } }; //类C继承类B2,B1。类B2,B1都继承自A。A类中成员变量的值和类继承的顺序有关系,最后继承的类会先赋值。 class C :public B2, public B1 { public: std::string cName; public: C(std::string b1, std::string b2, std::string c) :B1(b1), B2(b2), cName(c) {} C() { cName = "NO CNAME"; secondName = "NO SECONDNAME"; secondName2 = "NO SECONDNAME2"; } void OutName() { std::cout << "A name:" << firstName << " B2 name:" << secondName2 <<" B name:"<<secondName<<" C name:" << cName << std::endl; } };
接下来在main函数中调用。
#include”Class.cpp“
void main() { C c("li", "wang", "zhang"); c.OutName(); }
运行结果:
将类C继承顺序改为
运行结果:
结论:类C继承类B2,B1。类B2,B1都继承自A。A类中成员变量的值和类继承的顺序有关系,最后继承的类会先赋值。第一次最后继承的类为B1,A类成员firstName为3。第二次最后继承的类为B2,A类的成员firstName为1。