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

access private member variable through private member, same class

本文关键字:成员 变量 访问 一类      更新时间:2023-10-16
// 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(),并且在试图访问同一类members的私有成员char数组时得到错误。错误似乎说我应该指定它引用的是哪个类,为什么?我已经在定义中指定了类:

 int Set::find(char ch) {

据我所知,成员应该在函数定义的作用域中。我努力寻找任何多余的字符,我没有发现任何奇怪的,所有括号似乎都匹配。

问题在这里:

members.[i]

应该是

members[i]

中删除.
if (members.[i] == ch) return i;
~~~~~~~~~~~^