我正在学习C ++,并且我找到了这个赋值来创建一个简单的字符集数据结构。
(除了一些Java编程之外,我之前没有编程经验......)
本书即时阅读给了我一些我试过复制的代码......但它似乎没有用。
以下代码仅输出“The Set is {}”。
谁能告诉我我做错了什么?
我有一种感觉即我在添加函数中做错了...我不确定我是否完全理解C ++中的运算符重载但书写的就像我做的那样......所以......
/*
A set class for characters
*/
#include <iostream>
using namespace std;
const int maxSize = 100;
class Set {
char members[maxSize]; // Array that holds the set
int len; // number of members
// notice that find() function is private
int find(char c); // finds an element
public:
// Constucts a null set
Set() {
len = 0;
}
int getLength() {
return len;
}
void showset();
bool isMember(char c);
Set operator +(char c); // add element
Set operator -(char c); // remove element
Set operator +(Set ob2); // set union
Set operator -(Set ob2); // set difference
};
//returns -1 if not found.
int Set::find(char c) {
int i;
for (i = 0; i < len; i++) {
if (members[i] == c) return i;
return -1;
}
}
//prints the set.
void Set::showset() {
cout << "The Set is "<< "{ ";
for (int i = 0; i < len; i++) {
cout << members[i] << " ";
}
cout << " }" << "\n";
}
//checks if a character is a member of the set
bool Set::isMember(char c) {
if (find(c) != -1) return true;
return false;
}
Set Set::operator +(char c) {
Set newset;
if (len == maxSize) {
cout << "don't add elements to a full set dumbass...";
return *this; //existing set
}
//does element already exist?
if (find(c) == -1) { //if not then add
newset.members[newset.len] = c;
newset.len++;
}
return newset;
}
//overloads - operator so it removes element
Set Set::operator -(char c) {
Set newset;
int i = find(c);
//following for loop copies every element of the previous set into newset EXCEPT the one to be deleted
for (int j = 0; j < len; j++) {
if (j != i) {
newset = newset + members[j];
}
}
return newset;
}
// set union
Set Set::operator +(Set ob2) {
Set newset = *this;
//Add unique elements from second set
for (int i = 0; i < ob2.len; i++) {
newset = newset + ob2.members[i];
}
return newset;
}
//set difference
Set Set::operator -(Set ob2) {
Set newset;
//subtracts elements from second set
for (int i = 0; i < ob2.len; i++) {
newset = newset - ob2.members[i];
}
return newset;
}
//demonstration
int main() {
Set s1;
Set s2;
Set s3;
s1 = s1 + 'A';
s1 = s1 + 'B';
s1 = s1 + 'C';
s1.showset();
return 0;
}
答案 0 :(得分:1)
for (i = 0; i < len; i++) {
if (members[i] == c) return i;
return -1;
}
return -1
应该在for循环之外。您的查找函数始终返回0.(启用和注意编译器警告!)
除了len从未更新过0:
Set Set::operator +(char c) {
Set newset;
if (len == maxSize) {
cout << "don't add elements to a full set dumbass...";
return *this; //existing set
}
//does element already exist?
if (find(c) == -1) { //if not then add
newset.members[newset.len] = c;
newset.len++;
}
return newset;
}
上面的newset.len
中的将始终为0,因为newset
是一个新的对象外翻时间。
... 当然也是强制性的:如果你使用的是c ++并需要一套,你可以随时使用std中找到的那个
答案 1 :(得分:0)
Set :: len永远不会更新为0.更改该代码并重试:)