How to modify a value in a class? (C++) -
i'm trying add or subtract value in class, main file, seems reset value zero. being beginner don't understand why?! everytime print player.worldpositiony says either -1, 1, or 0 (if neither 1 or 2 selected - moveforward or moveback)
i have 2 simple files, main.cpp:
#include <iostream> #include "player.h" using namespace std; int keyboardinput; int main() { player player; cin.get(); cin >> keyboardinput; if (keyboardinput == 1){ player.moveforward(); } else if (keyboardinput == 2){ player.moveback(); } cout << "y: " << player.worldpositiony << endl; main(); } and player.h:
class player { public: int worldpositiony = 0; void moveforward(); void moveback(); }; void player::moveforward(){worldpositiony += 1;} void player::moveback(){worldpositiony -= 1;} i'm missing something. please help!
you're calling main recursively. don't want this, instead:
int main() { player player; while (true) { cin.get(); cin >> keyboardinput; if (keyboardinput == 1){ player.moveforward(); } else if (keyboardinput == 2){ player.moveback(); } cout << "y: " << player.worldpositiony << endl; } } calling main recursively means player object recreated every time input value, why values either -1 or 1.
Comments
Post a Comment