首页 > 解决方案 > 执行时预期的不合格 ID -> [0]

问题描述

我正在测试重载 [] 和 + 运算符,但出现了预期的不合格 ID,我不知道为什么。

顺便说一句,我在 Xcode 上使用谷歌测试。

错误发生在第 6 行和第 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]); }

这是速度类:

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

如果我使用 getX(),代码可以正常工作,但我不确定为什么不能使用 ->[]

标签: c++

解决方案


您可以这样做,但要使用正确的语法。例如,

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

推荐阅读