【发布时间】:2014-11-21 22:37:33
【问题描述】:
所以我有一个这样定义的类
template<class ItemType>
class Bag : public BagInterface<ItemType>
{
public:
Bag();
Bag(const ItemType &an_item); // contrusctor thats constructs for a signal item.
int GetCurrentSize() const;
bool IsEmpty() const;
bool Add(const ItemType& new_entry);
bool Remove(const ItemType& an_entry);
void Clear();
bool Contains(const ItemType& an_entry) const;
int GetFrequencyOf(const ItemType& an_entry) const;
vector<ItemType> ToVector() const;
private:
int GetIndexOf(const ItemType& target) const;
static const int kDefaultBagSize_ = 6;
ItemType items_[kDefaultBagSize_]; // array of bag items
int item_count_; // current count of bag items
int max_items_; // max capacity of the bag
我的教授特别要求我们使用该功能
void DisplayBag(const Bag<ItemType> &a_bag);
要在包中显示内容,问题是我不知道如何让它工作。 例如,在我的 int main 我有
Bag<string> grabBag;
grabBag.Add(1);
Display(grabBag);
然后在我的显示功能中我有。
void DisplayBag(const Bag<ItemType> &a_bag)
{
int j = 6;
for(int i = 0; i < j; i++)
{
cout << a_bag[i] << endl;
}
}
我尝试以多种方式弄乱此代码,但没有任何效果。我有
void DisplayBag(const Bag<ItemType> &a_bag);
在我的 int main() 和函数本身之前声明,它写在类实现的同一个头文件中。
向量函数
template<class ItemType>
vector<ItemType> Bag<ItemType>::ToVector() const
{
vector<ItemType> bag_contents;
for (int i = 0; i < item_count_; i++)
bag_contents.push_back(items_[i]);
return bag_contents;
} // end toVector
【问题讨论】:
-
这个类的定义似乎很可疑;为什么
Bag会有显示另一个Bag的方法? -
你确定
DisplayBag不是static? -
@OliverCharlesworth:注意“教授”这个词的使用。
-
如果你想让
grabBag显示自己的内容,那么根据界面你可以调用grabBag.Display(grabBag);。是的,这有点奇怪,但是你有一个奇怪的界面(如之前的 cmets 所述)。 -
@DavidK,我现在意识到我不应该在类中添加 displaybag() 函数。但现在我不知道下一步该做什么。那么我所有的内容都在a_bag 中的grabBag 中吗?我似乎无法从中调用任何东西。
标签: c++ function class templates abstract-data-type