通过私有成员,同一个类访问私有成员变量

时间:2015-08-21 12:43:25

标签: c++ class variables private member

// 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) {

据我了解,成员应该在函数定义的范围内。我很难找到任何奇怪的流浪角色,所有的括号似乎都匹配。

2 个答案:

答案 0 :(得分:3)

问题出在这里:

members.[i]

应该只是

members[i]

答案 1 :(得分:1)

中重新.
if (members.[i] == ch) return i;
~~~~~~~~~~~^