2011-08-11 175 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