我有一个类,private
其中有一个名为的成员变量,它是一个int
. 出于某种原因,如果我在方法中更改它的值(例如在构造函数上),它会改变得很好。但是,如果我在不同的方法上更改它并用于printf
在另一种不同的方法上输出其内容,则该值不会被结转并变成一个非常大的数字。
标题:
class Fruit {
private:
int m_fruitState; // 0 = IDLE, 1 = GROWING, 2 = READY, 3 = FALLEN, 4 = ROTTEN
int m_fruitTimer;
public:
Fruit ( );
int getFruitState( ); // Returns m_fruitState
void setFruitState( int fState );
void growFruit( CCTime dt ); // Called every 1 second (CCTime is a cocos2d-x class)
};
CPP
#include "Fruit.h"
Fruit::Fruit( ) {
// Set other member variables
this -> setFruitState( 0 ); // m_fruitState = 0
this -> m_fruitTimer = 0;
this -> m_fruitSprite -> schedule( schedule_selector( Fruit::growFruit ), 1.0 ); // m_fruitSprite is a CCSprite (a cocos2d-x class). This basically calls growFruit() every 1 second
}
int getFruitState( ) {
return this -> m_fruitState;
}
void setFruitState( int state ) {
this -> m_fruitState = state;
}
void growFruit( CCTime dt ) {
this -> m_fruitTimer++;
printf( "%d seconds have elapsed.", m_fruitTimer );
printf( "STATE = %d", this -> m_fruitState ); // Says my m_fruitState is a very big number
// This if condition never becomes true, because at this point, m_fruitState = a very big number
if ( this -> getfruitState( ) == 0 ) { // I even changed this to m_fruitState == 0, still the same
if ( this -> m_fruitTimer == 5 ) { // check if 5 seconds have elapsed
this -> setFruitState( 1 );
this -> m_fruitTimer = 0;
}
}
}
然后主要是创建 MyClass 的一个实例。
我不知道为什么会这样。为什么 C++ 会这样做,我该如何解决?提前致谢。