注册 登录
编程论坛 C++教室

弄成虚基类后就出现好多错误= =读不懂错误原因,怎么读懂

Orphan 发布于 2015-06-10 17:10, 469 次点击
#include<iostream>
using namespace std;
class vehicle
{protected:
   int wheel;
   int weight;
public:
   vehicle(int i,int j)
   {
     wheel=i;
     weight=j;
   }
   void display()
   {
     cout<<wheel<<endl;
     cout<<weight<<endl;
   }

};
class car:virtual public vehicle
{protected:
   int passengers;
public:
   car(int wh,int we,int p):vehicle(wh,we)
   {
     passengers=p;
   }
   void display()
   {
     cout<<wheel<<endl;
     cout<<weight<<endl;
     cout<<passengers<<endl;
   }

};
class truck:virtual public vehicle
{protected:
   double payload;
 public:
   truck(int wh,int we,double pay):vehicle(wh,we)
   {
     payload=pay;
   }
   void display()
   {
     vehicle::display();
     cout<<payload<<endl;
   }
      
};
class car_truck:public vehicle,public car,public truck
{protected:
   int flag;
public:
   car_truck(wh1,we1,p1,f):vehicle(wh1,we1,p1,f):car(wh1,we1,p1,f):truck(wh1,we1,p1,f)
   {
     flag=f;
   }
   void display()
   {
     if(flag==0)
     {
       cout<<"this is a car"<<endl;
       car::display();
     }
     else
     {
       cout<<"this is a truck"<<endl;
       truck::display();
     }
   }
      
};
int main()
{
   vehicle v(3,4);
   v.display();
   car c(3,4,5);
   c.display();
   truck t(3,4,8.4);
   t.display();
   car_truck ct(3,4,5,0);
   ct.display();
   return 0;

}
//Compiling...
.cpp
E:\dingzhw\dze\.cpp(51) : error C2584: 'car_truck' : direct base 'vehicle' is inaccessible; already a base of 'car'
        E:\dingzhw\dze\.cpp(4) : see declaration of 'vehicle'
E:\dingzhw\dze\.cpp(52) : error C2584: 'car_truck' : direct base 'vehicle' is inaccessible; already a base of 'truck'
        E:\dingzhw\dze\.cpp(4) : see declaration of 'vehicle'
E:\dingzhw\dze\.cpp(55) : error C2629: unexpected 'class car_truck ('
E:\dingzhw\dze\.cpp(55) : error C2334: unexpected token(s) preceding ':'; skipping apparent function body
E:\dingzhw\dze\.cpp(82) : error C2660: 'car_truck::car_truck' : function does not take 4 parameters
执行 cl.exe 时出错.

dze.exe - 1 error(s), 0 warning(s)
2 回复
#2
诸葛欧阳2015-06-10 18:54
这是多重继承的问题,你的car,trunk已经基础vehicale当你的car_trunk继承vehicle,car,trunk时其实继承了三个car
#3
rjsp2015-06-11 08:31
class car_truck:virtual public vehicle,public car,public truck
{protected:
   int flag;
public:
   car_truck(int wheel,int weight,int passengers,double payload,int flag_):vehicle(wheel,weight),car(wheel,weight,passengers),truck(wheel,weight,payload)
   {
     flag=flag_;
   }
1