【发布时间】:2017-10-11 17:38:41
【问题描述】:
我正在使用 C++ 为 OOP 进行“糖果店”分配项目,编译器再次抱怨我的代码 :) 我在论坛中发现了一个类似的命名主题,但它指出了一些其他问题...所以,我有一个基类来派生一些产品(糖果、饼干、vs.)和一个购物类的模板,如下所示:
class productBase{
protected:
string name;
double amount;
double ppAmount;
public:
productBase(){}
productBase(string na, double am, double pp){
name = na;
amount = am;
ppAmount = pp;
}
string getName() const;
double getAmount() const;
double getppAmount() const;
//virtual double getCost() const = 0; // make it abstract ?
};
// Templete for shopping
template <typename shopType>
class Shop {
private:
int noi; // number of items
double totalcost;
shopType * sTptr;
public:
Shop();
Shop(shopType);
~Shop() { delete[] sTptr; }
void add(shopType &);
void setDiscount(const double);
friend ostream& operator<<(ostream&, const Shop<shopType> &);
shopType operator[](int);
};
我的一个产品类是这样的:
class Cookie: public productBase {
private:
const double taxRate;
public:
Cookie() :taxRate(8) {}
Cookie(string nm, double am, double pp) :productBase(nm, am, pp), taxRate(8) {}
~Cookie() {}
double getCost() const;
friend ostream& operator<<(ostream &, Cookie &);
};
在程序中,我需要将我的产品保存在一个动态数组中,该数组首先创建并通过添加新实例进行扩展,如下所示:
int main() {
.....
Cookie cookie1("Chocolate Chip Cookies", 10, 180);
Cookie cookie2("Cake Mix Cookies", 16, 210);
Shop<Cookie> cookieShop(cookie1); // << this is where I am gettin error
cookieShop.add(cookie2);
.....
这是我从编译器收到错误的地方
在函数 _main
我认为它是由我的模板的构造函数引起的,并试图通过查看一些示例来修复它,例如通过引用传递和使用基类指针,甚至根本不使用基类,但我觉得是这个问题是其他东西,比如缺少参数或误用,但无法弄清楚:(所以这些是我正在寻找原因的模板类的方法......
template<typename shopType>
Shop<shopType>::Shop()
{
noi = 0;
totalcost = 0;
sTptr = NULL;
}
template<typename shopType>
Shop<shopType>::Shop(shopType sT) // I guess the problem is here
{
sTptr = sT;
noi++;
totalcost = sT.getCost();
}
template<typename shopType>
void Shop<shopType>::add(shopType & toAdd)
{
if (noi == 0) {
sTptr = new shopType;
sTptr = toAdd;
totalcost = toAdd.getCost();
noi++;
}
else {
shopType * ptr = new shopType[noi + 1];
for (int a = 0; a < noi; a++) {
ptr[a] = sTptr[a];
}
delete[] sTptr;
sTptr = ptr;
sTptr[noi++] = toAdd;
totalcost += toAdd.getCost();
}
}
这个模板的用法让我很困惑;如果不使用它我已经完成了,但另一方面我需要学习它:) 那么我可能错过了什么?
提前感谢您的任何指导或帮助。
【问题讨论】:
-
是的,模板的方法在一个单独的 shop.cpp 文件中,其中包括 shop.h 文件 (#include "shop.h"),该文件具有基类和模板类定义。跨度>
标签: c++ templates derived-class