gpt4 book ai didi

c++ - 将派生对象传递给模板

转载 作者:行者123 更新时间:2023-11-28 05:09:01 25 4
gpt4 key购买 nike

<分区>

我正在使用 C++ 为 OOP 开发一个“糖果店”作业项目,编译器再次提示我的代码 :) 我在论坛中发现了一个类似的命名主题,但它指出了一些其他问题...所以,我有一个基类来派生一些产品(糖果、 cookies 等)和一个购物类模板,如下所示:

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);
.....

这是我从编译器那里得到错误的地方

错误 LNK2019 未解析的外部符号“public: __thiscall Shop::Shop(class Cookie)” (??0?$Shop@VCookie@@@@QAE@VCookie@@@Z) 在函数 _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();
}
}

这个模板的用法让我很困惑;如果不使用它我就已经完成了,但另一方面我需要学习它:)那么我可能错过了什么?

在此先感谢您的指导或帮助。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com