我制作了一个可以容纳2种对象(int和double)的模板类,并尝试运行我的程序,但是出现错误,提示我的引用未定义,我不知道为什么
这是类标题:
template <class T>
class Product {
public:
T price;
Product(T price);
void Discount(int precentage);
T getPrice();
};
这是cpp类文件:
#include "Product.h"
template <class T>
Product<T>::Product(T price) :
price(price){};
template <typename T>
void Product<T>::Discount(int precentage) {
if(precentage != 0){
this->price = this->price * (precentage / 100);
}
}
template <typename T>
T Product<T>::getPrice() {
return this->price;
}
这是主要的:
#include <iostream>
#include "Product.h"
using namespace std;
int main( )
{
int x,y;
double w,z;
Product<int> p1(100);
Product<double> p2(50.0);
x = p1.getPrice();
p1.Discount(20);
y = p1.getPrice();
z = p2.getPrice();
p2.Discount(10);
w = p2.getPrice();
cout << "The price of the int product: " << x << endl;
cout << "The price of the int product after discount: " << y << endl;
cout << "The price of the double product: " << z << endl;
cout << "The price of the double product after discount: " << w << endl;
return 0;
}