【发布时间】:2015-11-15 10:00:21
【问题描述】:
// M9P369.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
const int MaxSize = 100;
using namespace std;
class Set {
int len; // number of members
char members[MaxSize]; // the set is stored in this array
int find(char ch); // find an element
public:
Set() { len = 0; } // constructor to make a null set initially
int getLength() { return len; } // return number of elements in the set
void showset(); // display the set
bool isMember(char ch); // check for membership
Set operator+(char ch); // overload operator to add an element to the set
Set operator-(char ch); // overload operator to remove an element from the set
Set operator+(Set ob2); // set Union - overloaded by the different type from above overload+ function
Set operator-(Set ob2); // set difference same as above.
};
// Return the index of the element passed in, or -1 if nothing found.
int Set::find(char ch) {
int i;
for (i=0; i < len; i++)
if (members.[i] == ch) return i;
return -1;
}
// Show the set
void Set::showset() {
cout << "{ ";
for (int i=0; i<len; i++)
cout << members[i] << " ";
cout << "}\n";
}
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
我正在学习运算符重载,遇到了类访问问题。
线
if (members.[i] == ch) return i;
给出工具提示错误“表达式必须具有类类型”,并编译错误:
\m9p369.cpp(34): error C2059: syntax error : '['
\m9p369.cpp(40): error C2228: left of '.showset' must have class/struct/union
\m9p369.cpp(41): error C2228: left of '.cout' must have class/struct/union
我正在定义类 Set 的私有成员函数 find(),但在尝试访问同一类成员的私有成员 char 数组时出现错误。错误似乎说我应该指定它所指的类,为什么?我已经在定义中指定了类:
int Set::find(char ch) {
据我了解,成员应该在函数定义的范围内。我努力寻找任何我找不到任何奇怪的杂散字符,所有括号似乎都匹配。
【问题讨论】:
-
提示:这是一个语法错误。它与访问无关。
-
您在
cout << members[i] << " ";中正确,但在if (members.[i] == ch)中错误...
标签: c++ class variables private member