#include<iostream> using namespace std; class Father { public: Father(string n) { name=n; cout<<"构造Father"<<endl;} ~Father() {cout<<"析构Father"<<endl;} void show() {cout<<"father's name-------------"<<name<<endl;} private: string name; }; class Mother { public: Mother(string n) { name=n;cout<<"构造Mother"<<endl;} ~Mother() {cout<<"析构Mother"<<endl;} void show() {cout<<"mother's name-------------"<<name<<endl;} private: string name; }; class Son:public Mother,public Father { public: Son(string n,string m,string f):Mother(m),Father(f)//============先构造的是父类,所以要先初始化父类的参数。 { name=n; cout<<"构造son"<<endl;} ~Son() {cout<<"析构son"<<endl;} void show() {cout<<"son's name------------"<<name<<endl;} private: string name; }; int main() { Son s("son","mother","father"); Son *p=&s; p->show(); Mother *q=&s; q->show(); Father *w=&s; w->show(); }
======================================================================
#include <iostream> using namespace std; class grand { double money; public: grand(double m) { money = m; cout << "create grand" << endl; } void look() { cout << "money=" << money << endl; } }; class father:virtual public grand { string first_name; public: father(string fn,double q):grand(q) { first_name = fn; cout << "create father" << endl; } void play_piano() { cout << "弹钢琴" << endl; } }; class mother:virtual public grand { string last_name; public: mother(string ln,double d):grand(d) { last_name = ln; cout << "create mother" << endl; } void dance() { cout << "会跳舞" << endl; } }; class uncle { public: void play_card() { cout << "打牌" << endl; } }; class you:public father,public mother { public: you(string s1,string s2,double d):father(s1,d),mother(s2,d),grand(d) { cout << "you" << endl; } }; int main() { you u("Job","Smith",1000); u.play_piano(); u.dance(); //u.father::look(); u.look();}