2016-07-28 99 views
-5

我在頭文件中定義了一個結構體。然後我有一個單身類,我試圖使用該結構。當我從另一個類中調用ResetVars()時,當它碰到test.numResponses =「TEST」行時,我得到一個訪問衝突。我認爲這與初始化有關,但我一直無法解決它。我是新來的C++,我不知道如何解決這個問題。謝謝你的幫助。寫入到typdef時出現C++訪問衝突struct

struct.h

typedef struct POLL_DATA 
{ 
    std::string numResponses; 
    std::string type; 
    std::string question; 
} POLL_DATA; 

ControlPolls.h

class ControlPolls 

{ 
    private: 
     static bool instanceFlag; 
     static ControlExitPolls *controlSingle; 
     ControlExitPolls(); 

     POLL_DATA test; 
    public: 

     static ControlExitPolls* getInstance(); 
     void ResetVars(); 
}; 

ControlPolls.cpp

#include "ControlPolls.h" 

bool ControlPolls::instanceFlag = false; 
ControlPolls* ControlPolls::controlSingle = NULL; 

//Private Constructor 
ControlExitPolls::ControlExitPolls() 
{ 
}; 

//Get instance 
ControlPolls* ControlPolls::getInstance() 

{ 
    if(!instanceFlag) 

    { 
     controlSingle = &ControlPolls(); 
     instanceFlag = true; 
     return controlSingle; 
    } 

    else 

    { 
     return controlSingle; 
    } 
} 

void ControlExitPolls::ResetVars() 
{ 

     test.numResponses = "TEST"; 
} 

callingClass.cpp

ControlPolls *controlSingleton; 
controlSingleton = ControlPolls::getInstance(); 
controlSingleton->getInstance()->ResetVars(); 
+1

請編輯您的問題包含一個[MCVE] – Slava

+3

爲什麼你需要'的typedef struct'在C++擺在首位? – Slava

+0

class A.h include struct.h – baruti

回答

2

你已經被C++的擊中最幸運解析,一個編譯規則說什麼可能是函數聲明函數聲明。罪魁禍首是這一行:

POLL_DATA testPoll(); 

testPoll被視爲一個函數的返回類型爲POLL_DATA聲明。嘗試刪除括號,或者簡單地寫POLL_DATA testPoll;,它隱式調用編譯器生成的默認構造函數。 另一個較大問題在於testPollA的成員,但是您隱藏了它並在構造函數A::A()中聲明瞭一個局部變量。我建議你完全刪除構造函數,因爲隱式構造函數就足夠了。

您的代碼一些更多的注意事項:

  • 你宣佈你的a類,但後來稱其爲A

  • 你已經寫了一個A的構造函數的實現,沒有聲明它像一個正確的前向聲明。

另外,在C++中不需要typedef struct。它是足夠的,並鼓勵他們寫:

struct POLLDATA { 
    ... 
}; 
+0

由於'POLL_DATA'具有一個默認的構造函數(由編譯器生成),因此不需要在ctor初始化程序列表或構造函數的主體中顯式初始化它。 'POLL_DATA testPoll = POLL_DATA()。'會創建一個本地,並且不會影響對象成員的實例化。此外,我看不出有任何跡象表明這可以解決OP隱含提到的問題。那麼這是如何解決OP沒有打算加入的錯誤呢? –

+0

根據您的評論進行編輯(這很明顯,我的赦免)並記錄了其他錯誤。 –

+0

@TimStraubinger嗯,它看起來更糟。 'POLL_DATA testPoll;'會有什麼意義? –