我无法理解如何构建子类。我的父类名为" package"孩子们被称为“隔夜”#34;和" twoDay"。包类处理收件人的姓名和地址以及包裹重量和每盎司的运费。 twoDay还增加了额外的运费,隔夜增加了每盎司运费。
包类文件运行正常,但我无法弄清楚如何在子构造函数中使用它。下面我将显示包和隔夜文件以及主程序文件的标题区域。
program.cpp
#include <iostream>
#include <string>
#include "package.h"
#include "twoDay.h"
#include "overnight.h"
int main() {
}
package.h
#include <string>
#include "name.h"
#include "address.h"
class package {
public:
package();
package(std::string initFirst, std::string initLast, std::string initLineOne,
std::string initLineTwo, std::string initCity, std::string initState,
std::string initZip, double initWeight, double initPrice);
double getWeight() const;
double getPrice() const;
double getCost() const;
private:
name recipientName;
address recipientAddress;
double weight;
double price;
};
package.cpp
#include "package.h"
package::package(){
recipientName = name();
recipientAddress = address();
weight = 0.0;
price = 0.0;
}
package::package(std::string initFirst, std::string initLast, std::string initLineOne,
std::string initLineTwo, std::string initCity, std::string initState,
std::string initZip, double initWeight, double initPrice)
: recipientName(initFirst,initLast), recipientAddress(initLineOne,initLineTwo,initCity,initState,initZip) {
weight = initWeight;
price = initPrice;
}
overnight.h
#include <string>
class overnight : public package {
public:
overnight();
overnight(std::string initFirst, std::string initLast, std::string initLineOne,
std::string initLineTwo, std::string initCity, std::string initState,
std::string initZip, double initWeight, double initPrice, double initOunceFee);
double getOvernightCost() const;
private:
package packageInfo;
double ounceFee;
};
overnight.cpp
#include "overnight.h"
overnight::overnight() {
packageInfo = package();
ounceFee = 0.0;
}
overnight::overnight(std::string initFirst, std::string initLast, std::string initLineOne,
std::string initLineTwo, std::string initCity, std::string initState,
std::string initZip, double initWeight, double initPrice, double initOunceFee)
: packageInfo(initFirst,initLast,initLineOne,initLineTwo,initCity,initState,initZip,initWeight,initPrice){
ounceFee = initOunceFee;
}
因此我遇到问题的部分是带有参数的daily.cpp的第二个构造函数。
答案 0 :(得分:1)
班级overnight
是 package
,您不需要合成并在班级中嵌入package
个对象。
至于构造函数,例如。
overnight::overnight(std::string initFirst, std::string initLast, std::string initLineOne,
std::string initLineTwo, std::string initCity, std::string initState,
std::string initZip, double initWeight, double initPrice, double initOunceFee)
: package(initFirst,initLast,initLineOne,initLineTwo,initCity,initState,initZip,initWeight,initPrice){
//^^^^^^^ Note the use of the base class here
ounceFee = initOunceFee;
}