Search code examples
c++classoperator-overloadingmember-variables

Class operators can not access member variables


I am working on an integer class that should be able to do basic arithmetic. The integer values are stored in an array where every array element holds two integer values. I convert this array of integers into the member variable integer.

class Integer {
private:
  char* arr;
  bool t;
  int integer;
  int arr_len;

public:
...
Integer operator-();
Integer operator+(Integer& i);
...
};  

The first operator is supposed to just negate the integer value. However, VS tells me that I do not have enough operator parameters. Further, I can not access the member variables in both operators and the stand alone integer is not defined.

Integer& operator-()
{
  Integer temp;
  temp.integer = -integer;;
  return temp;
}

Integer& operator+(Integer& i)
{
  Integer temp;
  temp.integer = integer + i.integer;
  return temp;
}

Solution

  • You have to indicate that the operators belong to the class Integer.

    To do so, add Integer:: before names of each operator.

    Also the signature in the definitions of operator doesn't match to the declarations. They return Integer in the declarations, but they are defined to return Integer&.

    Integer Integer::operator-()
    {
      Integer temp;
      temp.integer = -integer;
      return temp;
    }
    
    Integer Integer::operator+(Integer& i)
    {
      Integer temp;
      temp.integer = integer + i.integer;
      return temp;
    }