2011-08-11 3 views
8

아직 포인터와 참조를 잘 이해하지 못하고 있지만 정적 메서드와 변수가있는 클래스가 있으며 기본 클래스와 다른 클래스에서 참조됩니다. main()에 정의 된 변수가 있습니다. 정적 함수를 사용하여이 클래스의 변수에 전달하려고합니다. 이러한 함수가 main() 범위에서 볼 수있는 변수의 값을 변경하기를 원합니다.정적 포인터가있는 C++ 클래스

//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 

:

이것은 내가 뭘하려고 오전의 예입니다,하지만 난 컴파일러 오류를 얻을 ...

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

는 같은 클래스 외부 정적 변수의 정의를 제공합니다 그 외에도 위의 주석에 표시된대로 세미콜론을 잊어 버렸고 somefunctionbool 값을 반환해야합니다.

+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

이 코드는 질문에 대답 할 수 있지만, 어떻게 그리고/또는 왜 문제를 해결하는지에 대한 추가 컨텍스트를 제공하면 대답의 장기적인 가치가 향상됩니다. 품질에 대한 답변을 얻으려면이 [how-to-answer] (http://stackoverflow.com/help/how-to-answer)를 읽으십시오. – thewaywewere

관련 문제