c++ - 执行时预期的不合格 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(),代码可以正常工作,但我不确定为什么不能使用 ->[]
解决方案
您可以这样做,但要使用正确的语法。例如,
// 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));
推荐阅读
- linux - Ubuntu 初始配置脚本错误
- karate - 空手道 UI - 并行运行场景会引发错误“HttpHostConnectException:连接到 localhost:9222”
- mysql - 如何获取产品数据,如果客户有未签约的产品,但有关闭的产品
- java - 删除spring boot java reactor slf4j异常日志中的空新行
- python - 请求时间 - python
- kdb - KDB“值”范围作为局部变量
- plot - 在 colab 使用 networkx 绘制树
- java - 检查是否安装了 Linux“屏幕”包
- java - 需要使用复选框将选定的(多个)RecyclerView 项目行放在另一个带有 RecyclerView 的 Activity 中
- java - Spring Boot org.springframework.data.repository.config.BootstrapMode