簡體   English   中英

更改私有成員變量不會影響整個類

[英]Changing a private member variable does not affect the whole class

我有一個類,其中有一個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 ++會這樣做,我該如何解決? 提前致謝。

     changeInt( int newInt );       // Assume newInt = 5

從上面的行中刪除int

  void doSomething( ); {

刪除; 從上面一行。

更新:現在您缺少; 從頭文件的末尾開始。 修復了所有明顯的錯誤(可能會使它甚至無法編譯),對我來說很好用。 您粘貼的代碼與實際代碼之間仍然存在差異,或者您發現了編譯器錯誤。

Constructor: myInt = 0
changeInt( int ) : myInt = 5
After constructor and calling changeInt(), myInt = 5

在“選擇”參數schedule應該是一個SEL_SCHEDULE ,其中

typedef void(CCObject::* SEL_SCHEDULE)(float)

即它應該是CCObject的成員函數。
它也應該是您schedule 在其上調用的對象的成員,否則目標被調用時將是錯誤的。

我懷疑這

this -> m_fruitSprite -> schedule( schedule_selector( Fruit::growFruit ), 1.0 );

導致通話Fruit::growFruitthis指着精靈 ,而不是水果,這會導致各種不愉快的。
(請注意, schedule_selector執行C樣式強制轉換,這意味着它本質上是不安全的。請勿使用它。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM