Reputation: 21
I wanted to initialize 5 objects in the array with their positions (0,1,2,3,4). Is this just a syntax error? I feel like I am not properly using the pointers. Please help! Before anyone flags it as a duplicate, I am aware it is similar to a couple other questions but none of their solutions seem to work for me. Unless I'm doing it wrong, which I'll admit is possible, but that's why I'm here.
The output:
Code:
#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;
}
Upvotes: 0
Views: 120
Reputation:
You probably mean an array of them (not a pointer to one):
CuteRobot cr[5] = {0,1,2,3,4};
Then later use object rather than pointer notation:
cr[i].meet(cr);
...
Upvotes: 1