2014-06-12 3 views
-1

내가 열거 달 변수 중 하나를 사용하여 Date 객체를 초기화하기 위해 노력하고있어 정의되어 있지 않습니다 만, 컴파일러는식별자 "월은"

식별자 "월은"정의되지 않은 오류를주고있다

문제가 무엇인지 아는 사람이 있습니까? 당신이 Month m;를 이동하기 전에

#include<iostream> 
#include<string> 

using namespace std; 

class Year { 
    static const int max = 1800; 
    static const int min = 2200; 
public: 
    class Invalid {} ; 
    Year(int x) : y(x){ if (x < min || x >= max) throw Invalid(); } 
    int year() { return y; } 
private: 
    int y; 
}; 


class Date { 
private: 
    Year y; 
    Month m; // ERROR HERE 
    int d; 
public: 
    Date(Month m, int d, Year y) // ERROR HERE AT Mont m 
     :m(m), d(d), y(y) {} 
    void add_day(int n); 
    int month() {return m; } 
    int day() { return d; } 
    Year year() { return y; } 
    enum Month { jan =1, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec }; 
};  

Date today(Date::sep, 24, Year(1989)); 

void main() { 
    cout << today.day() << endl << today.month() << endl << today.year() << endl; 
}  
+8

u를 선언하기 전에'Month' enum을 사용하십시오. – Rakib

+0

달 선언은 어디에 있습니까? 나는 전에 사용하지 않고 그것을 볼 수 있습니다. – Jepessen

+0

@Rakibul 고마워, 어떤 이유로 든 수업에서 물건을 넣는 순서가 중요하지 않다고 생각 했어. – user3677061

답변

1

당신은 enum Month을 가지고 있습니다. 아직 정의되지 않은 클래스의 다른 변수에 액세스 할 수있는 인라인 함수 본문처럼 작동하지 않습니다.

하나의 옵션은 전체 정의를 개인 변수 앞에 올리거나 마지막에 개인 변수를 넣는 것입니다.

는 C++ 11에서는도 수행 할 수 있습니다 maincout 라인도 작업을 필요로

class Date 
{ 
    enum Month : int; // forward-declaration; requires type spec 
... 
    enum Month : int { jan = 1, ..... 
}; 

참고. today.year()은 그대로 cout으로 보낼 수 없습니다.

한 가지 옵션은 today.year().year()으로 변경하는 것입니다. 이것은 꼴 사나 지 않다. class Year 내에서 int year()이라는 더 나은 이름을 변경하는 것이 좋습니다. year_as_int() const.

또한
std::ostream &operator<<(std::ostream &os, Year const &y) 
{ 
    return os << y.year_as_int(); 
} 

멤버 변수를 수정하지 않는 모든 멤버 함수는 const 규정을 가져야한다 :

또한은 스트림 삽입 연산자 (이 아닌 클래스 정의 내, 파일 범위 임) 정의 할 . 다음 예제에서와 같이 const 참조 만있는 객체에서 호출 할 수 있습니다. 이를 해결하기 위해

0

한 가지 방법은 처음 사용하기 전에 위치에 enum Month의 정의를 이동하는 것입니다.

#include <iostream> 

using namespace std; 

class Year { 
    static const int max = 2200; 
    static const int min = 1800; 
public: 
    class Invalid {} ; 
    Year(int x) : 
      y(x) 
    { 
     if (x < min || x >= max) throw Invalid(); 
    } 
    int year() { return y; } 
private: 
    int y; 
}; 


class Date { 
public: 
    enum Month { jan =1, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec }; 
private: 
    Year y; 
    Month m; // ERROR HERE 
    int d; 
public: 
    Date(Month m, int d, Year y) // ERROR HERE AT Mont m 
     :m(m), d(d), y(y) {} 
    void add_day(int n); 
    int month() {return m; } 
    int day() { return d; } 
    Year year() { return y; } 
};  


int main() { 
    Date today(Date::sep, 24, Year(1989)); 

    cout << today.day() << endl << today.month() << endl << today.year().year() << endl; 
} 


/* 
    Local Variables: 
    compile-command: "g++ -g test.cc" 
    End: 
*/ 

주, 시공에 당신이 today.year이 필요하다는 것을() 년()에서 출력 또는 Year에 대해 <<을 정의하십시오. 또한 Year에서 minmax에 대한 값이 바뀌 었습니다.