0 c++
我有一个练习,其中我必须使用模板类“Garage”,该类将“汽车”或“自行车”作为参数。很简单,但我不断收到错误,因为我显然对模板的理解不够好。这是 :
template<class Car>
class Garage{
Car array[10];
public:
void addCar(int counter1);
void removeCar(int counter1);
void displayContents(int counter1);
};
template<class Motorbike>
class Garage{
Motorbike array[10];
public:
void addMotorbike(int counter2);
void removeMotorbike(int counter2);
void displayContents(int counter2);
};
Run Code Online (Sandbox Code Playgroud)
恰当的 ?我是否必须在类的每个函数前面插入模板?该程序当然包含更多的类和函数,但它是我需要在头脑中整理出来的模板。感谢您抽出宝贵的时间。
如果您必须为每个实例化专门编写每个实现,那么首先就不需要模板。您可以为您的课程命名CarGarage,MotorbikeGarage然后就到此为止。您可能想要类似的东西:
template<class VehicleType>
class Garage{
VehicleType array[10];
public:
void addVehicle(int counter1);
void removeVehicle(int counter1);
void displayContents(int counter1);
};
Run Code Online (Sandbox Code Playgroud)
从这个类模板(它不是模板类,没有模板类。是Garage模板,不是类)中,您可以实例化Garage<Car>具有 s 数组Car作为成员的类型和Garage<Motorbike>具有 s 数组作为Motorbike成员的类型。
成员函数的实现需要在头文件中(参见为什么模板只能在头文件中实现?)。最简单的方法是在模板内内嵌定义它们。
| 归档时间: |
|
| 查看次数: |
2408 次 |
| 最近记录: |