有没有办法让构造函数自动理解参数类型?



我有一个Feature类,里面有一个public vehicle_type,我有 3 个vehicle_type变量的候选者;CarTruckMotor类。当我为Feature类调用构造函数时,我希望我的程序自动获取使用构造函数调用的车辆类型。我实际上尝试使用Templates来解决问题,但它不起作用。所以,有人可以告诉我如何在使用或不使用Templates的情况下实现这一目标.

这是我Feature.h文件:

#ifndef FEATURE_H
#define FEATURE_H
#include <string>
#include "../includes/Car.h"
#include "../includes/Truck.h"
#include "../includes/Motor.h"

template <typename T>
class Feature{
public:
Feature();
Feature(int w, std::string b, std::string clr, double p, T v_t);
T vehicle_type;
int wheels;
std::string brand;
std::string color;
double price;
};

#endif

这是我Feature.cpp文件:

# include "../includes/Feature.h"
template <typename T> 
Feature::Feature(int w, std::string br, std::string clr, double p, T v_t){wheels = w; brand=br; color = clr; price=p;  vehicle_type = v_t; }
Feature::Feature(){}

最后,下面是我将鼠标悬停在Feature.cpp文件中Feature构造函数上时发生的错误。

name followed by '::' must be a class or namespace name

请随时询问更多信息。谢谢。

看起来您只需要提供模板声明并修复语法:

template <typename T> 
Feature<T>::Feature(int w, std::string br, std::string clr, double p, T v_t);
template<class T>
Feature<T>::Feature();

相关内容

最新更新