2011-08-11 43 views
8

我不明白指針和引用,但我有一個靜態方法和變量,將從主和其他類引用的類。我有一個在main()中定義的變量,我想通過靜態函數將其傳遞給此類中的變量。我希望這些函數能夠更改main()作用域中所顯示的變量的值。C++類與靜態指針

這是什麼,我試圖做一個例子,但我得到的編譯器錯誤...

class foo 
{ 
    public: 

    static int *myPtr; 

    bool somfunction() { 
     *myPtr = 1; 
     return true; 
    } 
}; 

int main() 
{ 
    int flag = 0; 
    foo::myPtr = &flag; 

    return 0; 
} 
+11

通常,無論何時出現編譯器錯誤,_always_將它們包含在問題中。 –

回答

15

類的外部提供的靜態變量的定義:

//foo.h 
class foo 
{ 
    public: 

    static int *myPtr; //its just a declaration, not a definition! 

    bool somfunction() { 
     *myPtr = 1; 
     //where is return statement? 
    } 
}; //<------------- you also forgot the semicolon 


///////////////////////////////////////////////////////////////// 
//foo.cpp 
#include "foo.h" //must include this! 

int *foo::myPtr; //its a definition 

除此之外,您還忘記了上述註釋中所示的分號,somefunction需要返回bool值。

+0

'foo :: somfunction'也需要返回一個值 – Praetorian

+0

我收到以下錯誤:無效使用限定名'foo :: myPtr' – Brian

+0

@Brian:照我說的去做。那麼你不會得到任何錯誤。 – Nawaz

0
#include <iostream> 
using namespace std; 

class foo 
{ 
public: 

static int *myPtr; 

bool somfunction() { 
    *myPtr = 1; 
    return true; 
} 
}; 
////////////////////////////////////////////////// 
int* foo::myPtr=new int(5);  //You forgot to initialize a static data member 
////////////////////////////////////////////////// 
int main() 
{ 
int flag = 0; 
foo::myPtr = &flag; 
return 0; 
} 
+0

儘管此代碼可能會回答問題,但提供有關如何解決問題和/或爲何解決問題的其他上下文可以提高答案的長期價值。請閱讀此[如何回答](http://stackoverflow.com/help/how-to-answer)以提供高質量的答案。 – thewaywewere