2017-10-23 7 views
0

저는 C++을 처음 사용하며 날짜 함수를 구현하는 클래스를 작성하고 있습니다. 이 프로그램은 운영자 <<and>>C++ 연산자가 개인 데이터 변수 오버로드 및 액세스

에게 코드에 대한 링크를 오버로드에 대한 두 개의 비 멤버 함수 bool printDate(const Date& d)string intToString(const int& n) 2 개 친구 기능을 가지고하는 것은 https://repl.it/NC2H/37

내가

'std::__cxx11::string Date::month' is private within this context `, 

` ambiguous overload for 'operator<<' (operand types are 'std::basic_ostream<char>' and 'const Date')` 
and 

`note: declared private here` 

코드 같은 오류가 계속입니다 :

 #include<iostream> 
     #include<vector> 
     #include<string.h> 
     #include<ctype.h> 
     #include<algorithm> 
     using namespace std; 

     const vector<string> months{ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; 


     string intToString(const int& n){ 
     return to_string(n);   //inbuilt function 
     } 


     class Date{ 
     //Private members 
     string month; 
     int day; 
     int year; 


     bool isValidMonth() const{ 
      return day==daysInMonth(m); 
     } 

     int daysInMonth(const string& m) const{ 
      vector<string>::iterator m_index; 
      if(find(months.begin(),months.end(),m)!=months.end()){ 
      m_index=find(months.begin(),months.end(),m); 
      } 
      int month_index=distance(months.begin(),m_index)+1; 
      switch(month_index) 
      { 
      case 2: return isLeapYear()?29:28; 

      case 1: 
      case 3: 
      case 5: 
      case 7: 
      case 8: 
      case 10: 
      case 12: 
        return 31; 

      default: 
        return 30; 
      } 

     } 
     bool isLeapYear() const{ 
      if(year%4==0){ 
      if(year%100==0 && year%400==0){  //2000 is leap year but 1900 is not 
       return true; 
       } 
      else{ 
       return false; 
      } 
      } 
      else{ 
      return false; 
      } 
     } 
     string toString(){ 
      string result_date; 
      result_date=intToString(day)+"-"+month+"-"+intToString(year); 
      return result_date; 
     } 
     public: 

     friend istream& operator >>(istream& is, Date& d); 
     friend ostream& operator <<(ostream&os ,const Date); 
     //public constructor 
     Date(const string& m="January",const int& d=1,const int&y=2000){ 
      month=m; 
      day=d; 
      year=y; 
     } 

     void setMonth(const string& m){ 
      month=m; 
     } 
     void setDay(const int& d){ 
      day=d; 
     } 
     void setYear(const int& y){ 
      year=y; 
     } 

     string getMonth()const{ 
      return month; 
     } 
     int getDay() const{ 
      return day; 
     } 
     int getYear() const{ 
      return year; 
     } 
     void Month(){ 
      if(!month.empty()) 
      { 
       month[0]=toupper(month[0]); 
       for(int i=1;i<month.length();++i) 
        month[i]=tolower(month[i]); 
      } 
     } 
     bool isValidDate() const{ 
      //calls isValidMonth() to check if days match 
      if(isValidMonth()){ 
       return true; 
      } 
      return false; 
     } 


     }; 




     istream & operator >>(istream & is, Date& d){ 
     //overloads the >>operator, which reads 
     cout<<"\n Enter the day of the date \n"; 
     cin>>d.day; 
     cout<<"\n Enter the month of the date \n"; 
     cin>>d.month; 
     cout<<"\n Enter the year of the date \n"; 
     cin>>d.year; 
     return is; 
     } 

     ostream & operator <<(ostream & os ,const Date& d){ 
     os<<d.day<<"."<<d.month<<"."<<d.year; 
     return os; 
     } 
     bool printDate(const Date& d){ 
     // if(!d.isValidDate()){ 
     if(!d.isValidDate()){ 
      cerr<<"("<<d<<"): not valid date"; 
      return false; 
     } 
     cout<<"("<<d<<")"; 
     return true; 
     } 
     int main(int argc, char const *argv[]) 
     { 
     // code for testing purposes 
     Date defaultDate; 
     printDate(defaultDate); 
     cout<<endl; 
     /*  
     Date moonLanding("jul",20,1969); 
     printDate(moonLanding); 
     cout<<endl; 
     moonLanding.setMonth("july"); 
     printDate(moonLanding); 
     cout<<endl; 

     Date leapDay("Ferbruary",29,2001); 
     printDate(leapDay); 
     cout<<endl; 
     leapDay.setDay(28); 
     printDate(leapDay); 
     cout<<endl; 

     Date d; 
     cout<<d.getMonth()<<" "<<d.getDay()<<", "<<d.getYear<<endl; 

     d.setMonth("July"); 
     d.setDay(4); 
     d.setYear(1776); 
     printDate(d); 
     cout<<endl; 

     while(cin>>d){ 
      d.Month(); 
      bool flag=printDate(d); 
      cout<<endl; 
      if(flag) cout<<d.toString()<<endl; 
     } 
     */  
     return 0; 
     } 

프로그램 실행은 다음과 같습니다

main.cpp: In function 'std::ostream& operator<<(std::ostream&, const Date&)': 
main.cpp:133:17: error: 'int Date::day' is private within this context 
      os<<d.day<<"."<<d.month<<"."<<d.year; 
       ^~~ 
main.cpp:19:14: note: declared private here 
      int day; 
       ^~~ 
main.cpp:133:29: error: 'std::__cxx11::string Date::month' is private within this context 
      os<<d.day<<"."<<d.month<<"."<<d.year; 
          ^~~~~ 
main.cpp:18:17: note: declared private here 
      string month; 
       ^~~~~ 
main.cpp:133:43: error: 'int Date::year' is private within this context 
      os<<d.day<<"."<<d.month<<"."<<d.year; 
              ^~~~ 
main.cpp:20:14: note: declared private here 
      int year; 
       ^~~~ 
main.cpp: In function 'bool printDate(const Date&)': 
main.cpp:139:23: error: ambiguous overload for 'operator<<' (operand types are 'std::basic_ostream<char>' and 'const Date') 
      cerr<<"("<<d<<"): not valid date"; 
      ~~~~~~~~~~^~~ 
main.cpp:132:19: note: candidate: std::ostream& operator<<(std::ostream&, const Date&) 
     ostream & operator <<(ostream & os ,const Date& d){ 
+1

"클래스는 두 개의 비 멤버 함수가"- 어떤 클래스는 멤버 함수를 가질 수 있습니다 :) –

+0

을 유일한 문제는 '>>'연산자 인 경우를, 무엇을 정확히는 자지 손에 들고있는 문제와 아무 관련이없는 모든 멤버 함수를 포함하는 대용량의 코드 더미를 버려야합니까? –

+1

오류 메시지에 대해 명확하지 않은 점은 무엇입니까? 1) ostream & operator << (ostream & os, const Date & d)'에 비공개 멤버를 사용하려고 시도하고 있지만, 친구로 표시되어 있지 않습니다. 2) 'const Date'로 호출 할 수있는 것은 무엇이든간에 'const Date'로 호출 할 수 있으며 그 반대의 경우도 마찬가지입니다. 그러므로 모호한 호출 오류. –

답변

4

친구 선언은 실제 운영자를 일치하지 않습니다 실제 운영자가 참조를 허용하는지

friend ostream& operator <<(ostream&os ,const Date); 
... 
ostream & operator <<(ostream & os ,const Date& d) 

참고.

0

친구 문제에 대한 문체 수정, 스트리밍을 구현하고, 구성원이기 때문에이 그 성가신 private 변수에 액세스 할 수 있습니다라는 공공의 멤버 함수라고 인쇄, 추가로 : 그런 다음

ostream& print(ostream& str)const 

을 외부 운영자 < < 사소한된다 :.

ostream& operator <<(ostream& str, const MyClass& inst) 
{ 
    return inst.print(str); 
}