0

I'm testing overloading [] and + operator, but Expected unqualified-id occurs and I have no idea why.

BTW, I'm using google test on Xcode.

The error occurs on line 6 and 7

TEST (Speed, operatorPlus) {
Speed speed_0(3, 4);
Speed speed_1(5, 6);
Speed * speed_add = speed_0 + speed_1;

ASSERT_EQ(8, speed_add->[0]);
ASSERT_EQ(10, speed_add->[1]); }

And here's the Speed class:

class Speed {
public:
    Speed (double x, double y) {
        this->x = x;
        this->y = y;
    }

    double getAbsSpeed () const {
        return sqrt(x * x + y * y);
    }

    double & operator [] (int index) {
        if (index == 0)
            return x;
        else if (index == 1)
            return y;
        else
            throw (std::string)"index error";
    }

    Speed * operator + (Speed & s) const {
        return new Speed(x + s[0], y + s[1]);
    }

    double & getX () {
        return x;
    }

    double & getY () {
        return y;
    }


private:
    double x = 0;
    double y = 0;
};

The code works fine if I use getX(), but I'm not sure why can't I use ->[]

  • `operator+` should return a `Speed` not a `Speed *` See: https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading – Richard Critten May 10 '18 at 05:40
  • 2
    `->[` is a syntax error. The right-hand side of the `->` operator must be the name of a class member. – M.M May 10 '18 at 05:52
  • Don't use `new` or pointers, they are not needed in this program. Return by value. `operator+` should accept an argument by value or by const reference. – n. m. could be an AI May 10 '18 at 05:54

2 Answers2

2

You can do it, but with proper syntax. For example,

// x is an object and a is pointer to an object
x.operator[](y); // x[y]
a->operator[](b);  // (*a)[b]
x.operator+(y);  // x + y
a->operator+(b); // (*a) + b

speed_add->operator[](0); // (*speed_add)[0]
ASSERT_EQ(8, speed_add->operator[](0));
ASSERT_EQ(10, speed_add->operator[](1));
jblixr
  • 1,345
  • 13
  • 34
1

I would modify operator+ return to Speed (not a pointer).

From @M.M's comment:

argument to be taken by const reference (or value... basically anything except non-const reference!)

double operator [] (int index) const { // modified
    // same body
}

Speed operator+(const Speed& s) const { // modified to const reference
    return Speed(x + s[0], y + s[1]);
}

then calling it would be:

Speed speed_0(3, 4);
Speed speed_1(5, 6);
Speed speed_add = speed_0 + speed_1;

assert(8 == speed_add[0]);
assert(10 == speed_add[1]); 
Joseph D.
  • 11,804
  • 3
  • 34
  • 67
  • Another improvement would be for the argument to be taken by const reference (or value... basically anything except non-const reference!) – M.M May 10 '18 at 05:53
  • @M.M, thank you for your suggestion. modified the answer. – Joseph D. May 10 '18 at 06:12