2012-10-16 2 views
0

내 코드에 정적 메서드로 파일을 컴파일하려고 시도했습니다. 내 computeCivIndex()은 사용자로부터 5 개의 입력을 가져 와서 계산을 수행하고 float 값을 되 돌리려고합니다.정적 메서드로 컴파일하는 동안 오류가 발생했습니다.

this.sunType은 java 구문이지만 V ++의 경우 둘 모두가 동일한 이름 인 경우 어떻게 연결해야합니까?

내 코드에는 getter 및 setter 메서드가 있고 게시하기에는 너무 긴 두 생성자가 있습니다.

test.cpp:159: error: cannot declare member function ‘static float LocationData::computeCivIndex(std::string, int, int, float, float)’ to have static linkage 
test.cpp: In static member function ‘static float LocationData::computeCivIndex(std::string, int, int, float, float)’: 
test.cpp:161: error: ‘this’ is unavailable for static member functions 

코드 :

class LocationData 
{ 
    private: 
    string sunType; 
    int noOfEarthLikePlanets; 
    int noOfEarthLikeMoons; 
    float aveParticulateDensity; 
    float avePlasmaDensity; 
    public: 
    static float computeCivIndex(string,int,int,float,float); 
}; 
static float LocationData::computeCivIndex(string sunType, int noOfEarthLikePlanets,int  noOfEarthLikemoons, float aveParticulateDensity, float avePlasmaDensity) 
{ 
    this.sunType = sunType; 
    this.noOfEarthLikePlanets = noOfEarthLikePlanets; 
    this.noOfEarthLikeMoons = noOfEarthLikeMoons; 
    this.aveParticulateDensity = aveParticulateDensity; 
    this.avePlasmaDensity = avePlasmaDensity; 
    if(sunType == "Type O") 
     //and more for computation 
} 

답변

3

static 선언 static 구현에서 연기

내 오류입니다. 정적 구현은 함수 심볼이 구현 된 파일 내에서만 사용 가능하다는 것을 의미합니다.

단순히 함수 구현 전에 정적을 제거하십시오. 게다가 정적 함수는 클래스 함수이므로 클래스의 비 정적 멤버에 액세스 할 수 없습니다. 그것들은 객체 인스턴스없이 사용되도록되어 있습니다. 그래서 인스턴스 변수가 없습니다.

float LocationData::computeCivIndex(string sunType, int noOfEarthLikePlanets,int  noOfEarthLikemoons, float aveParticulateDensity, float avePlasmaDensity) 
{ 
} 
2

는 컴파일러 오류가 나에게 합리적으로 명확 같다 : 기본적으로

error: ‘this’ is unavailable for static member functions

, 회원이 static 때문에,이 유형의 특정 인스턴스의 컨텍스트 내에서 실행되지 않습니다 - 그래서 this를 사용하여 방법 내에서 의미가 없다. 너 this, 따라서 오류를 사용해보십시오. MSDN documentation for static에서

: 당신이 정적 인 것으로 멤버를 선언하지 않으처럼

When you declare a member function in a class declaration, the static keyword specifies that the function is shared by all instances of the class. A static member function cannot access an instance member because the function does not have an implicit this pointer. To access an instance member, declare the function with a parameter that is an instance pointer or reference.

소리가 난다.

(제쳐두고, "클래스의 모든 인스턴스에서 공유 됨"이라고하는 설명이 마음에 들지 않습니다. 클래스의 특정 인스턴스와 관련이 없다는 생각을 선호합니다. 인스턴스를 만들었습니다.)

+0

내 숙제는 정적 메소드 여야하므로 링크 할 수있는 방법이 있습니까? –

+0

@HengAikHwee : 이상한 요구 사항처럼 들립니다. 인스턴스에 대한 참조를 가져 오기 위해 서명을 변경할 수 있습니까? 대신 새 인스턴스를 반환 할 수 있습니까? –

+0

흠, LocationData 데이터를 의미합니까? data.sunType = sunType; ? –

관련 문제