2015-11-03 82 views
0

我有幾個班在我的C++應用程序的結構,像這樣:C++修改實例變量聲明在父類

  /- RedFixture 
Fixture -- 
      \- BlueFixture 

因此,夾具基類有兩個子類。

我想封裝基類內的一些常用功能,以及存儲一些常用屬性。一個例子是我們稱之爲「當前」的簡單整數。基類聲明如下:

class Fixture 
{ 
    public: 
    int current; 

    Fixture(); 

    virtual void loop(); 

    int next(); 

    int prev(); 
}; 

下和以前的方法是非常簡單的,並且從字面上是由一些條件和current++current--

我的代碼中的其他地方,我有一個指向Fixture的指針,雖然指針的實際類型可能是RedFixtureBlueFixture。當我打電話給fixture->next()時,我看不到currentRedFixtureBlueFixture的執行loop()的內部發生變化。

RedFixture/BlueFixture聲明如下:

實施例的 RedFixture/ BlueFixture的實施 loop(),其中I訪問 current可變
#ifndef RedFixture_H 
#define RedFixture_H 

#include "Fixture.h" 

class Animation; 

class RedFixture : public Fixture { 
    public:  
    /** 
    * Construct a new fixture 
    */ 
    RedFixture(); 

    /** 
    * Setup the fixture and perform any initialization necessary 
    */ 
    virtual void setup(); 

    /** 
    * Perform the loop 
    */ 
    virtual void loop(); 
}; 

#endif 

void RedFixture::loop() 
{ 
    Animation *currentAnim = animations.at(current); 
    currentAnim->animate(leds); 
} 

而且,在一些其它點在代碼中,我有這樣的事情:

Fixture *fixture = fixtures.at(0); 
fixture->next(); 

我期望current屬性被增加,並有這反映了下一次調用loop(),但事實並非如此。而是,current變量似乎不會改變。

鑑於我是C++新手,我誤解了繼承的工作原理嗎? current計數器是否應該正確修改,即使我正在使用多態性並在Fixture類型的指針上調用next()prev()

+1

你可以發佈你的RedFixture和BlueFixture類的例子嗎?我需要看看你在你的實現中做了什麼。 – Riptyde4

+0

你必須有一些其他的邏輯錯誤。如果一個類從一個超類繼承,然後修改了一個從超類繼承的成員變量,那麼對象的靜態類型是什麼並不重要,變量應該改變 - 多態不應該影響任何東西,它應該隻影響什麼函數叫做。注意你的訪問修飾符,也許你正在調用next()?。 – Riptyde4

+1

你不會誤解繼承本身,它應該工作。父母和孩子班級之間的增量變化是否實施?尤其是,子代碼是否使用了一些只存在於子代中的變量等等? – deviantfan

回答

0

下面的代碼打印:

Nothing 
1 

希望這回答了你的一些關於多態性以及它如何可能涉及到你的代碼的問題。對不起,如果我屠殺你的功能的預期目的,但只是想給你一些背景。

#include <iostream> 
using namespace std; 

class Fixture{ 
public: 
    int current = 0; 
    virtual void loop(){ 
     cout << "Nothing" << endl; 
    } 
    void next(){ 
     current++; 
    } 
}; 


class AwesomeFixture : public Fixture{ 
    public: 
     void next(){ 
      // Do nothing 
      cout << "Nothing" << endl; 
     } 
     virtual void loop(){ 
      next(); 
     } 
}; 

int main(int argc, char * argv[]){ 

    Fixture * fixture = new AwesomeFixture(); 
    fixture->loop(); 
    fixture->next(); 
    cout << fixture->current << endl; 

    return 0; 
}