2012-03-06 63 views
2

問題:通過C++函數,我需要運行線程函數,該函數又調用另一個Singleton C++函數。這個被調用的函數會調用C函數(它運行一個無限循環來改變每10毫秒的嵌入式系統狀態)。如何在C++中調用函數內部的函數?

問題:如何在C++中調用函數內的函數?我是否需要分配實例來調用第二個函數?

請參考示例代碼並給出您的想法是否正確或錯誤。
我有一個單獨的類說辛格爾頓

class Singleton 
{  
    private : // constructors and values 
    public : 
      void runThread(); 
      Singleton getInstance(); 
      bool ChangeStatus(int a);  
    }; 

void Singleton:: runThread() 
{  
    changeStatus(7); // is this is right way to call function inside function 
} 

bool Singleton:: changeStatus(int a); 
{ 
    // This calls C function which changes the status of embedded system 
}  

void main() 
{ 
    // create instance of singleton class 

    Singleton *instance1 = Singleton::getInstance(); 

    instance1.runThread();  
    /* will this call the function changeStatus and will this  
     changeStatus function will change status of embedded system 
     assuming the c function to change status is working fine. 
    */ 
} 

請無視基本的語法錯誤。
當我打電話從主要的runThread功能將它成功地調用changeStatus功能還是需要指定一個多實例內runThread調用changeStatus像辛格爾頓 instance2 = Singleton::getInstance(); instance2->changeStatus

+2

您有問題要問?如果是這樣,那是什麼? – 2012-03-06 22:30:59

+0

對不起基思,我不是很清楚。我更新了我的問題。請參考它,並分享您的想法 – samantha 2012-03-06 22:36:45

+1

** void ** getInstance(); ? instance1 **。** runThread(); ? – 2012-03-06 22:37:47

回答

1

寫入的函數調用是正確的。當你在一個不是靜態的成員函數中,並且你調用另一個成員函數時,它會在同一個實例上調用它。如果您需要訪問指向調用函數的實例的指針,則還可以使用關鍵字this

所以你也可以寫this->changeStatus(7);它也可以正常工作。

這就是說,我應該從閱讀你的代碼中警告你,現在寫的不是創建一個新的線程,而是在主線程中運行該函數。如果你想產生一個額外的線程,你需要代碼來具體做到這一點。它也不會重複檢查任何內容,但這些可能是您爲了簡化問題而省略的細節。

+0

嗨基思,感謝您的答覆。那麼我對使用這個指針有點困惑,但你已經清除了我的疑惑。感謝那。也是,我已經寫了很多細節來簡化事情。 – samantha 2012-03-07 17:44:56

2

在代碼編寫(修正後所有明顯的錯誤)Singleton::runThread(),當在instance1上調用時,確實會在相同的instance1上調用Singleton::changeStatus(int)

+0

謝謝celtschk。 – samantha 2012-03-06 23:29:25