【问题标题】:class function toString() C++类函数 toString() C++
【发布时间】:2019-02-10 19:26:47
【问题描述】:

我有一个名为 Set 的类,其中定义了一个函数,该函数应该将集合作为其等效字符串返回。我在理解如何实施这一点方面遇到了重大问题,因为我的老师没有很好地解释要做什么。任何方向性的帮助或解释将不胜感激。我已经发布了我的教授想要的设置。

edit1:为了清楚起见,我了解如何临时实现大多数其他功能,但由于某种原因,toString() 函数真的不适合我。此外,我们专门为我们提供了函数的名称以使用这种方式,因此 Union 应该大写,因为它会干扰另一个命令。

#include <iostream>
#include <algorithm>
#include <set>
#include <iterator>


class Set
{
public:
    void add(int i);
    bool belongs(int i);
    void difference(Set B);
    void Union(Set B);
    void intersect(Set B);
    std::string toString();
};

int main()
{
    Set A;
    Set B;

    std::cout << "printing A" << std::endl;
    A.toString();
    std::cout << std::endl << "printing B" << std::endl;
    B.toString();
    std::cout << std::endl << "adding 12 to A" << std::endl;
    A.add(12);
    std::cout << std::endl << "printing A" << std::endl;
    A.toString();
    std::cout << std::endl << "does 4 belong to A" << std::endl;
    A.belongs(4);
    std::cout << std::endl << "does 11 belong to A" << std::endl;
    A.belongs(11);
    std::cout << std::endl << " remove B from A" << std::endl;
    A.difference(B);
    std::cout << std::endl << "printing A" << std::endl;
    A.toString();
    std::cout << std::endl << "union of A and B" << std::endl;
    A.Union(B);
    std::cout << std::endl << "printing A" << std::endl;
    A.toString();
    std::cout << std::endl << "intersecting A and B" << std::endl;
    A.intersect(B);
    std::cout << std::endl << "printing A" << std::endl;
    A.toString();
}

//add the number i to the set
void Set::add(int i)
{

}

//return true if i is a member of the set
bool Set::belongs(int i)
{

}

//removes B from the set A where A is the current set so A=A-B
void Set::difference(Set B)
{

}

//performs A U B where A is the current set and the result is stored in A
void Set::Union(Set B)
{

}

//performs A B where A is the current set and the result is stored in A
void Set::intersect(Set B)
{

}

//displays the set in roster notation {1, 2, 3} etc
std::string Set::toString()
{

}

【问题讨论】:

  • 那么实际的问题是什么?我们不是来解释你的老师希望你做什么或为你做什么。
  • 除非这是本练习的要求,否则我建议您创建一个to_string 函数,然后它会镜像std::to_string 的功能。您的函数当然可以使用对象中现有的toString 成员函数。
  • 另外请尽量保持名称和符号一致。与其他成员函数相比,Union 这个名字很突出。一致性使代码更易于阅读、理解和维护(对于大型项目非常重要)。请注意,所有大写名称通常用于宏或其他符号常量。从一开始就养成好习惯,以后就不必考虑了。
  • 恐怕你问得太早了。 Set 还没有任何成员可以转换为字符串。也就是说,从toString方法开始是正确的想法。在调试其他功能时将非常宝贵。

标签: c++ function set tostring


【解决方案1】:

您的教授希望您做的是编写一个函数std::string Set::toString(){ ... },它将返回一个std::string,其中包含您的对象内部容器的元素(根据您的函数,我怀疑可能是一个std::vector),它将返回一个包含正确格式元素的字符串。

您将需要研究如何迭代内部容器并将元素附加到您使用string::append 返回的字符串。希望这是足够的方向来实际开始使用该功能并实现它,因为它相当简单。在追加之前,您可能需要使用to_string() 方法将整数转换为字符串。

【讨论】:

  • @keeperkell13 欢迎
猜你喜欢
  • 2021-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-29
  • 2012-10-26
  • 2012-07-22
相关资源
最近更新 更多