【发布时间】: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方法开始是正确的想法。在调试其他功能时将非常宝贵。