【发布时间】:2021-08-13 20:21:56
【问题描述】:
我必须对汽车和车辆进行分类我正在尝试使用参数化构造函数来设置 Car 对象成员的值,但它会给出错误
#include <iostream>
#include <string>
class vehicle {
int wheels ;
double price ;
std::string color ;
public:
vehicle(int , double , std::string ) ;
void initialize (int , double , std::string ) ;
~vehicle (void) ;
};
class car : public vehicle {
int load ;
double weight ;
public:
car (int , double , int wheels , double price , std::string color ) ;
void initialize (int , double , std::string , int , double ) ;
~car (void) ;
};
car::car(int load , double weight , int wheels , double price , std::string color ): vehicle (wheels ,price , color )
{
this->load = load ;
this->weight = weight ;
}
vehicle::vehicle(int w,double p,std::string c)
{
initialize(w,p,c);
}
void vehicle::initialize(int w,double p,std::string c)
{
wheels = w;
price = p;
color = c;
}
它在汽车构造函数行中给出错误
【问题讨论】:
-
car::car(int load , double weight , Engine engi )-- 这与类中的声明不匹配。声明有 6 个参数——这也应该有 6 个参数。 -
“它给出了错误”。有什么错误?
-
德鲁·多尔曼。 'car' 的构造函数必须显式初始化没有默认构造函数的基类 'vehicle' 和预期的 '{' 或 ',
-
另外(忽略定义未声明的构造函数的错误)这个
car::car(int load , double weight , Engine engi ): vehicle (int wheels ,double price , std::string color )是错误的。car的构造函数的初始化列表需要给vehicle构造函数传值,比如car::car(int load , double weight , Engine engi ): vehicle (4 , 10000, RED )其中4代表轮子数量,10000代表特定价格,RED指定红色. -
@Peter 我按照你说的编辑了代码,它给了我同样的错误
car::car(int load , double weight, int wheels , double price, std::string color ) : vehicle ( wheels , price , color )
标签: c++ class inheritance constructor