#include
using namespace std;
class vihicle
{
public:
int i;
virtual void run()
{
cout<<"111";
}
};
class bicycle:virtual public vihicle
{
public:
void run()
{
cout<<"bicycle run";
}
};
class motorcar:virtual public vihicle
{
public:
void run()
{
cout<<"motorcar run";
}
};
class mb:public bicycle
{
public:
virtual void run1(){}
void run()
{
run1();
}
};
class mm:public motorcar
{
public:
virtual void run2(){}
void run()
{
run2();
}
};
class motorbicycle:public mb,public mm
{
public:
void run1()
{
cout<<"8888";
}
void run2()
{
cout<<"7777";
}
};
int main()
{
motorbicycle d1;
bicycle a1;
vihicle *b2=&a1;
vihicle *b3=&d1;
bicycle *pB1=&d1;
motorcar *pB2=&d1;
b3->run();
b2->run();
pB1->run();
pB2->run();
cout<<d1.i;
while (1)
{
}
return 0;
}
#if 1
#include
using namespace std;
class vihicle
{
public:
int i;
virtual void run()
{
cout<<"111";
}
};
class bicycle:virtual public vihicle
{
public:
void run()
{
cout<<"bicycle run";
}
};
class motorcar:virtual public vihicle
{
public:
void run()
{
cout<<"motorcar run";
}
};
class mb:public bicycle
{
public:
virtual void run1(){}
void run()
{
run1();
}
};
class mm: public motorcar
{
public:
virtual void run2(){}
void run()
{
run2();
}
};
class motorbicycle: public mb, public mm
{
public:
//void run(){}
void run1()
{
cout<<"8888";
}
void run2()
{
cout<<"7777";
}
};
int main()
{
motorbicycle d1;
bicycle a1;
vihicle *b2=&a1;
vihicle *b3=&d1;
bicycle *pB1=&d1;
motorcar *pB2=&d1;
b3->run();
b2->run();
pB1->run();
pB2->run();
cout<<d1.i;
}
#endif
注意我雙斜槓注釋的那一行,語法是沒有錯,但是代碼邏輯是錯的,你想要同時繼承兩個類,沒有問題,但是編譯器並不知道你想要繼承哪一個run()
方法。因為你的 bicycle類和你的motorcar類已經將父類的run()方法給覆蓋掉了,那就是說你的 motorbicycle類必須得覆蓋以上兩個類中的run()方法
否則,編譯器怎麼能夠知道,該繼承哪個呢? 當然,以上注釋是一種解決方案,還有一種就是,在你的 bicycle類和你的motorcar類中不要定義run()
方法,這樣的話就可以過去了,當然,請根據你當下的需求來,還有就是你好像不理解虛擬繼承的本質,好好補補基礎...