【问题标题】:Class templates - Removing an item from a "box" object类模板 - 从“盒子”对象中删除项目
【发布时间】:2016-09-11 18:04:04
【问题描述】:

我已经发布了要点here

这是一门数据结构课程。我们正在创建一个简单的 PlainBox 类并创建成员函数,这些函数允许我们在“盒子”中添加和删除项目,检查盒子是否为空,并检查私有数据成员的值。我的作业中的所有内容都已完成,除了一件事:我不知道如何创建 remove() 函数,以便我们可以从已经包含某些内容的框中删除一个项目。

这里是说明:“向模板类添加一个名为“remove”的公共方法。该方法将没有参数并返回一个bool值。如果盒子中有一个项目,则应该删除该项目(make框为空),该方法应返回true(任务完成)。否则,不要修改框并返回false(任务无法执行)。”

remove() 函数位于 PlainBox.cpp 文件中。我只是很困惑如何将“ItemType item”变量重置为默认值,以便该框为空。我应该将'item'设置为空字符串吗? (item = " ";)

template<class ItemType>
bool PlainBox<ItemType>::remove()
{
    if (full == true)
    {
        full = false;
        return true;
    }
    else
    {
        return false;
    }
}

在 main.cpp 文件的底部,我正在测试 secondNumberBox 上的 remove() 函数,然后检查私有成员变量是否为空。

这里是 PlainBox 类供参考:

// Declaration for the class PlainBox
class PlainBox: public BoxInterface<ItemType>   // added parent class
{
private:
   // Data field
   ItemType item;
   bool full;

public:
   // Default constructor
   PlainBox();

   // Parameterized constructor
   PlainBox(const ItemType& theItem);

   // Accessor method to get the value of the data field
   ItemType getItem() const;

   // Add method
   bool add(const ItemType& theItem);

   // Remove method
   bool remove();

   // isEmpty method
   bool isEmpty();

}; // end PlainBox

我希望我对这篇文章的措辞正确,如果这没有任何意义,请告诉我!

【问题讨论】:

  • 发布minimal reproducible example(http:www.stackoverflow.com/help/mcve)
  • 任何相关代码都必须在帖子中,而不是在链接中。还要确保创建一个minimal reproducible example
  • 我已经更新了我的帖子,如果现在可以接受请告诉我:)
  • == true 是多余的。就我个人而言,我会将item 设为指针。
  • 顺便说一句,模板必须进入头文件。你不能在 cpp 文件中实现它们(如果你想在其他 cpp 文件中使用它们)。

标签: c++ class templates


【解决方案1】:

为什么要弄乱项目?您有一个标志(bool full),表示是否使用了 item。我相信你有一个方法可以在标志为假时写入项目。如果 bool full 为假,写作方法是否关心项目中的内容?

【讨论】:

  • 我想你是对的。出于某种原因,我认为我应该做的不仅仅是将 bool 设置为 false。我倾向于过度思考这些事情......
猜你喜欢
  • 1970-01-01
  • 2011-04-15
  • 2021-08-01
  • 2018-10-15
  • 1970-01-01
  • 1970-01-01
  • 2021-11-11
  • 2019-02-28
相关资源
最近更新 更多