所以我有一个课程,包括Car,Route和Taxi。我使用合成来获取Car和Route类的数据。每个类都需要能够在其上输入数据并输入要检查的数据。我如何使用Taxi类的构造函数与他使用的方式有关,并使用Car和Route类的get / set方法检查数据。
如何访问setRouteTaxidata
方法中的参数?
有什么建议吗?
class RouteTaxi {
private:
int id;
public:
Car car;
Route route;
RouteTaxi();
~RouteTaxi();
void setRouteTaxidata(string cbrand, string cmodel, int cyears, int cseatingCapacity, double cloadCapacity, double cfuelConsumption,string rnodes, double rrouteLength, int rtoursPerDay, int i);
};
RouteTaxi::RouteTaxi(){
setRouteTaxidata(??) ??????
}
void RouteTaxi::setRouteTaxidata(string cbrand, string cmodel, int cyears, int cseatingCapacity, double cloadCapacity, double cfuelConsumption, string rnodes, double rrouteLength, int rtoursPerDay, int i){
car.setBrand(cbrand);
}
答案 0 :(得分:0)
构造函数RouteTaxi()是默认构造函数。它必须创建一个没有任何这些的有效对象,因此您必须具有可接受的默认值。
没有好的方法来制作默认路线,除非你的“无处”路线带有“nocar”汽车,所以你可以在构造函数中要求这些参数,如下例所示:
#include<string>
using std::string;
class Car {
public:
Car(string cbrand, string cmodel, int cyears, int cseatingCapacity, double cloadCapacity, double cfuelConsumption){}
};
class Route {
public:
Route(string rnodes, double rrouteLength, int rtoursPerDay){}
};
class RouteTaxi
{
private:
int id;
public:
Car car;
Route route;
RouteTaxi(string cbrand, string cmodel, int cyears, int
cseatingCapacity, double cloadCapacity, double cfuelConsumption,
string rnodes, double rrouteLength, int rtoursPerDay, int i)
: car(cbrand, cmodel, cyears, cseatingCapacity, cloadCapacity, cfuelConsumption),
route(rnodes, rrouteLength, rtoursPerDay),
id(i)
{}
static RouteTaxi generate_from_console_input();
};
// this is a factory function (class static member of RouteTaxi)
RouteTaxi RouteTaxi::generate_from_console_input() {
// input from console
string cbrand, cmodel, rnodes;
int cyears, cseatingCapacity, rtoursPerDay, i;
double cloadCapacity, cfuelConsuption, rrouteLength;
// return the object
// this is an error, using uninitialized data, simply because I am not actually getting the data from the console. You will do that, so it will not be a problem.
return RouteTaxi(cbrand, cmodel, cyears, cseatingCapacity, cloadCapacity, cfuelConsuption, rnodes, rrouteLength, rtoursPerDay, i);
}
注意冒号和初始化列表,构造函数在执行自己的构造函数体之前使用它来初始化其他对象。 http://en.cppreference.com/w/cpp/language/initializer_list
工厂生成器是另一种创建对象的方法。在调用实际构造函数之前,您需要所有信息,因此...在实际调用构造函数之前编写一个获取它的函数。
这是众所周知的设计模式。见https://en.wikipedia.org/wiki/Creational_pattern。虽然这些更详细。您没有处理很多不同类型的RouteTaxi和子类。