【发布时间】:2021-05-31 15:32:21
【问题描述】:
我想用它们的位置 (0,1,2,3,4) 初始化数组中的 5 个对象。这只是语法错误吗?我觉得我没有正确使用指针。请帮忙!在有人将其标记为重复之前,我知道它与其他几个问题相似,但他们的解决方案似乎都不适合我。除非我做错了,我承认这是可能的,但这就是我在这里的原因。
输出:
代码:
#include <iostream>
using namespace std;
class CuteRobot{
private:
int position; //x-axis position
public:
CuteRobot(){};
CuteRobot(int p){ //initialize default position
position = p;
}
void getPosition(){ //getter
cout << "position: "<< position;
}
CuteRobot& move(int steps){ //Positive number for forward motion, negative number for backward motion.
//Ideally, implement function chaining here, CuteRobot& move(int steps);
if(steps >=1){
position = position + steps;
} else {
position = position - steps;
}
return *this;
}
void meet(CuteRobot* cr){ //The function takes a pointer parameter, calculates the steps value when the cr object meets this objectect,
// assuming this object stands still, and use move() function to bring cr object to this object position.
int steps = (this->position) - (cr->position);
cr->move(steps);
}
};
int main()
{
CuteRobot* cr[5] ={0,1,2,3,4}; // array of five CuteRobot objects.
for(int i =1; i < 5; i++){ //loop through the array and use meet() method to bring every robots to zero position
//(where the first robot stands)?
cr[i]->meet(cr[0]);
cr[i]->getPosition();
}
return 0;
}
【问题讨论】:
-
好的,如果我将
CuteRobot* cr[5] ={0,1,2,3,4};更改为CuteRobot* cr{ new CuteRobot[5]{0,1,2,3,4}};我不再收到 invalid conversion error 但我确实收到 error: base operand of '- >' 对于cr[i]->meet(cr[0]);和cr[i]->getPosition();具有非指针类型'CuteRobot'
标签: c++ syntax-error