Search code examples
c++classvariablesprivatemember

access private member variable through private member, same class


// 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;
}

I am learning operator overloading, and came across a class access problem.

The line

if (members.[i] == ch) return i;

Gives a tooltip error 'expression must have class type', and compile errors:

\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

I am defining the private member function find() of class Set, and I get the error upon trying to access the private member char array of the same class, members. Error seems to say I should specify which class it's referring to, why? I already specify the class in the definition:

 int Set::find(char ch) {

As I understand, members should be in the scope of the function definition. I looked hard for any stray characters I couldn't find anything odd, all parenthesis seem to match.


Solution

  • Problem is here:

    members.[i]
    

    It should be just

    members[i]