尝试编译派生类时收到此错误。这是我第一次使用继承的类,所以我不确定是什么问题。
(编辑:我一直在研究这个项目并稍微改了一下。另外,这里是来自我的编译器的错误消息。如果有帮助的话,这就是整个事情https://repl.it/LYwt/8)
#ifndef SHOPPINGCART_H
#define SHOPPINGCART_H
#include <iostream>
#include <iomanip>
#include "Bag.h"
#include "item.h"
template<class ItemType>
class shoppingcart : public Bag<ItemType>
{
private:
float totalPrice;
public:
shoppingcart();
double getTotalPrice();
bool add(item);
bool remove(item);
};
#endif
头文件:
#include "shoppingcart.h"
using namespace std;
template <class ItemType>
shoppingcart<ItemType>::shoppingcart() : totalPrice(0.00)
{
}
template <class ItemType>
bool shoppingcart<ItemType>::add(const item newProduct)
{
bool added = Bag<ItemType>::add(newProduct);
totalPrice = totalPrice + (newProduct.getitemQuantity() * newProduct.getitemPrice());
return added;
}
template <class ItemType>
bool shoppingcart<ItemType>::remove(const item aProduct)
{
bool removed = Bag<ItemType>::remove(aProduct);
totalPrice = totalPrice - (aProduct.getitemQuantity() * aProduct.getitemPrice());
return removed;
}
float price;
template <class ItemType>
double shoppingcart<ItemType>::getTotalPrice()
return totalPrice;
}
错误消息:
shoppingcart2.cpp:5:1:错误:'shoppingcart'没有命名类型 shoppingcart :: shoppingcart():totalPrice(0.00) ^ ~~~~~~~~~~~
shoppingcart2.cpp:11:18:错误:'&lt;'之前的预期初始值设定项代币 bool shoppingcart :: add(const item newProduct) ^
shoppingcart2.cpp:21:18:错误:'&lt;'之前的预期初始值设定项代币 bool shoppingcart :: remove(const item aProduct) ^
shoppingcart2.cpp:31:20:错误:'&lt;'之前的预期初始值设定项代币 double shoppingcart :: getTotalPrice()
答案 0 :(得分:0)
这是你在找什么?
#include <iostream>
#include <string>
template<class ItemType>
class Bag
{};
template<class ItemType>
class shoppingCart : public Bag<ItemType>
{
private:
double totalPrice;
public:
shoppingCart<ItemType>(){ }
double calculateTotal(const ItemType& item_price, const ItemType& item_quantity);
};
template<class ItemType>
double shoppingCart<ItemType>::calculateTotal(const ItemType& item_price, const ItemType& item_quantity)
{
totalPrice = getitemPrice() * getitemQuantity();
}
struct an_item
{
double cost;
std::string name;
};
int main( )
{
shoppingCart<an_item> cart;
return 0;
}
在探索代码时,在一个cpp文件中完成所有操作,编写和共享更加容易。这个巨大的是item&
,你没有声明它。我假设您真的想使用ItemType&
作为参考。但是对我来说这并没有多大意义,因为你把它称为价格和数量。因此,如果ItemType
是一个类,您将不得不专门化它。或者你打算成为POD?如果您为代码使用一个文件并发布整个文件,我真的很有帮助。