2014-03-28 4 views
0

클래스를 선언하는 헤더 파일이 있는데이 클래스가 기본 cpp C++ 파일 (즉 클래스 '1'이 아닌 다른 파일)에 선언 된 정수에 액세스하려고합니다. . 나는 Google에서 검색 중이며 관련성이 없다고 판결했습니다. 어떻게해야합니까?C++ 클래스 헤더 파일의 전역 정수에 액세스

+2

는'extern' 같은 헤더 파일 정수를 선언 – jsantander

답변

0

main.cpp의 정수를 함수로 옮기고 함수를 정적으로 만들고 함수가 해당 함수에 대한 참조를 반환하도록하고 함수를 클래스 헤더 파일 (또는 구현 파일 if 적절한) 포함합니다.

integer.h가 :

#ifndef INTEGER_H // use some better, longer name here 
#define INTEGER_H 

int &Integer(); 

#endif 

integer.cpp : 정수 같은

#include "integer.h" 

int &Integer() 
{ 
    static int i = 0; 
    return i; 
} 

액세스 :

int x = Integer(); // copy 

Integer() = 123; // assign 
0

소스 파일에서 특정 전역 변수를 공유하려면를 사용 extern 키워드

MAIN.CPP

#include "foo.h" 

int global_var=0; 

int main() 
{ 
    foo(); 
    return 0; 
} 

foo.h

#ifndef FOO_H 
#define FOO_H 

extern int global_var; 

void foo(); 

#endif 

foo.cpp에

#include "foo.h" 

int foo() 
{ 
    global_var=1; 
} 
관련 문제