这是我的代码:
class package
{
protected:
string name;
string city;
string state;
int zip;
double weight;
double costPerOunce;
public:
package::package(string Name, string City, string State, int Zip, double Weight, double CostPerOunce):
name(Name), city(City), state(State),
zip(Zip), weight(Weight), costPerOunce(CostPerOunce)
{
}
double calculateCost()
{
return (weight * costPerOunce);
}
};
class twoDayPackage: public package
{
protected:
double flatFee;
public:
twoDayPackage::twoDayPackage(double FlatFee):
flatFee(FlatFee)
{
}
double calculateCost()
{
return (weight * costPerOunce) + flatFee;
}
};
int main()
{
system ("pause");
return 0;
}
我尝试运行此代码,我得到的错误如下: 错误C2512:'package':没有合适的默认构造函数
错误与基类构造函数的继承有关,但我不确切知道代码未运行的原因。请帮帮我。
答案 0 :(得分:4)
twoDayPackage::twoDayPackage(double FlatFee):
flatFee(FlatFee)
正在调用基础构造函数package()
,因为您尚未指定任何其他内容。
在课程包中添加一行package::package(){};
:)
答案 1 :(得分:3)
你需要一个包的构造函数。
同样,在声明构造函数时也不需要package::package(...)
(这是在cpp文件中定义的时候。)只需package(...)
即可。
class package
{
protected:
string name;
string city;
string state;
int zip;
double weight;
double costPerOunce;
public:
package()
{}
// \/ You don't need package:: that's only needed when you define the func in cpp
package(
string Name, string City, string State, int Zip,
double Weight, double CostPerOunce
)
: name(Name), city(City), state(State),
zip(Zip), weight(Weight), costPerOunce(CostPerOunce)
{
}
double calculateCost()
{
return (weight * costPerOunce);
}
};
答案 2 :(得分:2)
在构建twoDayPackage
之前,package
的构造函数将首先创建flatFee
。由于你没有告诉它如何做到这一点,它寻找一种构建package
的默认方式。
构建twoDayPackage
时,您需要为构建基础package
提供所需的一切。要么是,要么确定要传递给package
构造函数的值。
传递所需的参数如下所示:
class twoDayPackage {
public:
twoDayPackage(string Name, string City, string State, int Zip, double Weight, double CostPerOunce, double flatFee) :
package(Name, City, State, Zip, Weight, CostPerOunce),
flatFee(flatFee) {
}
//..
};