2014-01-05 39 views
0

您好,我有一些問題,理解編譯器對這段代碼抱怨什麼。非法使用非靜態數據成員

template<typename T> struct sEventColl { 
T __d__; 
list<string> event_list; 


sEventColl(T d, const string& eventStr) : 
     __d__(d) { 
    event_list.push_back(eventStr); 
} 

template<typename U> 
sEventColl(const sEventColl<U>& other) { 
    __d__ = other.__d__; 

    this->event_list.clear(); 

    for (typename list<string>::const_iterator it = 
      other.event_list.crbegin(); it != other.event_list.crend(); 
      it++) { 
     event_list.push_back(*it); 
    } 
} 

~sEventColl(){} 

bool operator<=(const T & d) const { 
    return ((d == __d__) || (__d__ < d)); 
} 

bool operator>=(const T & d) const { 
    return ((__d__ == d) || (__d__ > (d))); 
} 

bool removeEvent(string eventText) { 

    for (typename list<string>::iterator it = event_list.begin(); 
      it != event_list.end(); it++) { 
     if (*it == eventText) { 
      event_list.erase(it); 
      return true; 
     } 
    } 
    return false; 
} 

bool addEvent(const string event) { 

    /* Check if object already exist */ 
    for (typename list<string>::const_iterator it = event_list.begin(); 
      it != event_list.end(); it++) { 
     if (event == *it) 
      return false; 
    } 
    event_list.push_back(event); 
    return true; 
} 

bool isEmpty() { 
    return event_list.empty(); 
} 

friend ostream& operator<<(ostream & os, const sEventColl & ecoll) { 
    for (typename list<string>::const_iterator it = ecoll.cbegin(); 
      it != event_list.cend(); it++) { 
     os << __d__ << " : " << *it << endl; 
    } 
    return os; 
} 

};從編譯器

輸出:

calendar.h: In function 'std::ostream& lab2::operator<<(std::ostream&, const lab2::sEventColl&)': calendar.h:49:16: error: invalid use of non-static data member 'lab2::sEventColl::event_list' calendar.h:110:11: error: from this location calendar.h:48:4: error: invalid use of non-static data member 'lab2::sEventColl::d' calendar.h:111:10: error: from this location

+0

看起來像這個問題一樣的問題:https://stackoverflow.com/questions/16002417/invalid-use-of-non-static-data-member-when-accessing-a-templated-class-field? rq = 1 –

+0

即時通訊這樣一個白癡,剛剛意識到我實際上是一個靜態訪問數據成員在運算符<<方法..這解決了我的問題 –

+1

'__d__'是一個[保留名稱。](http:// stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-ac-identifier) –

回答

0

解決吧..

friend ostream& operator<<(ostream & os, const sEventColl & ecoll) { 
for (typename list<string>::const_iterator it = ecoll.cbegin(); 
     it != event_list.cend(); it++) { 
    os << __d__ << " : " << *it << endl; 
} 
return os; 

}

我應該通過ECOLL參考已訪問的成員!