75.6k views
3 votes
Implement a class Bug that models a bug climbing up a pole. Each time the up member function is called the bug climbs 10 cm. Whenever it reaches the top of the pole (at 100 cm), it slides back to the bottom. Also, implement a member function reset() that starts the Bug at the bottom of the pole and a member function get_position that returns the current position. (Fill in the code for the functions with dotted bodies) #include using namespace std; class Bug { public: int get position() const; void reset(); void up(); private: int position = 0; }; int Bug::get position() const { } void Bug: : reset() { } void Bug:: up) { } int main() { Bug bugsy; Bug itsy bitsy; bugsy.reset(); itsy bitsy.reset(); bugsy.up(); bugsy.up(); cout << bugsy.get position() << endl; cout << "Expected: 20" << endl; itsy bitsy.up(); itsy bitsy.up(); itsy bitsy.up(); cout << itsy bitsy.get position() << endl; cout << "Expected: 30" << endl; for (int i = 1; i = 8; i++) { bugsy.up(); } cout << bugsy.get_position() << endl; cout << "Expected: 0" << endl; bugsy.up(); cout << bugsy.get_position() << endl; cout << "Expected: 10" << endl; return 0; }

User Jxstanford
by
8.2k points

1 Answer

1 vote

Final answer:

The question involves the implementation of a class 'Bug' which simulates a bug climbing up a pole in C++ programming. Key methods are 'get_position', 'reset', and 'up' which control the bug's position on the pole, with 'up' handling the logic of resetting the position when the top is reached.

Step-by-step explanation:

The question asks for the implementation of a class Bug in C++ that simulates the behavior of a bug climbing up a pole. The bug climbs in increments of 10 cm and resets back to the bottom when it reaches the top of a 100 cm pole. The class includes methods to reset the bug's position, make it climb up the pole, and get its current position.

The get_position method returns the current position of the bug. The reset method sets the bug's position back to zero. The up method increases the bug's position by 10 cm, but if the position reaches 100 cm or more, it resets the bug back to the bottom of the pole.

Example Code:

int Bug::get_position() const {
return position;
}

void Bug::reset() {
position = 0;
}

void Bug::up() {
position += 10;
if (position >= 100) {
position = 0;
}
}

User Gabriel Mazetto
by
7.2k points