将对象传递给模板构造函数或方法的正确方法是什么

时间:2017-05-12 22:27:53

标签: c++ arrays object

我有一个Shop模板类和一个Cookie类,并尝试创建一个Cookie类型的动态数组(或者其他类似的,因为它是一个模板),如果需要,在我的主函数中添加更多,如:

template <typename shopType>
class Shop {
private:
    int noi;                 // number of items
    double totalcost;   
    shopType * sTptr;        // for dynamic array
public:
    Shop(shopType &);
    void add(shopType &);
    .....

int main() {
.....
    Cookie cookie1("Chocolate Chip Cookies", 10, 180);  
    Cookie cookie2("Cake Mix Cookies", 16, 210);

    Shop<Cookie> cookieShop(cookie1);       // getting error here
    cookieShop.add(cookie2);                // and here
.....

使用我写的构造函数和方法:

template<typename shopType>
Shop<shopType>::Shop(shopType & sT)
{
    sTptr = new shopType;
    sTptr = sT;                           // not allowed, how can I fix ?
    noi = 1;
    totalcost = sT.getCost();
}

template<typename shopType>
void Shop<shopType>::add(shopType & toAdd)
{
    if (noi == 0) {
        sTptr = new shopType;
        sTptr = toAdd;                   // not allowed, how can I fix ?
        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();
    }
}

我很自然地得到 C2440'=':无法从'Cookie'转换为'Cookie *'错误...

我理解我做错了什么,但我无法弄清楚如何以正确的方式做到这一点......

是否应该创建一个新的Cookie指针并将参数中的一个复制到它可以工作,还是其他什么?有什么建议 ?提前谢谢。

1 个答案:

答案 0 :(得分:3)

编译器的错误消息非常清楚。您正尝试将shopType分配给行中的shopType*

sTptr = toAdd;

除非您有充分理由自行管理阵列内存,否则请使用std::vector将对象存储在Shop中。

template <typename shopType>
class Shop {
   private:
      // There is no need for this.
      // int noi;                 // number of items
      double totalcost;   
      std::vector<shopType> shopItems;

      // ...
};

然后,Shop::add可以简单地实现(我将参数类型更改为const引用):

template<typename shopType>
void Shop<shopType>::add(shopType const& toAdd)
{
   shopItems.push_back(toAdd);
}