我想,如果我讓運算符< <的朋友 一個數據結構(按名稱排列);運算符<<不能使用它的朋友的IT成員,數組
//Forward Declarations
template<typename S, typename T>
struct array;
template<typename U, typename V>
ostream& operator<< (ostream& ous, const array<U, V>& t);
然後,我將能夠做到這樣的事情;運營商實施< <
//operator<< is a friend of struct array{} already
template<typename T, typename U>
ostream& operator<< (ostream& os, const array<T, U>& var){
if(var){
/*Error: 'IT' was not declared in this scope*/
for(IT it = var.data.begin(); it != var.data.end(); it++){
/*and i thought i need not redeclare IT before using it
since operator<< is a friend of array already*/
}
}
else{cout << "empty";}
return os;
}
現在裏面,這裏是數組的實現:
/*explicit (full) specialization of array for <type, char>*/
template<>
template<typename Key>
struct array<Key, char>{
//data members
map<const Key, string> data;
typedef map<const Key, string>::iterator IT;
//member function
friend ostream& operator<< <>(ostream& ous, const array& t);
//other stuff/functions
};
最後,編譯器很生氣,當我試駕了它像這樣;
void Test(){
array<int, char> out;
out[1] = "one"; //Never mind. this has been taken care of
out[2] = "two";
cout << out; //Error: 'IT' was not declared in this scope
}
問: 究竟我做錯了,或者,我爲什麼不能dirrectly訪問和使用 IT(陣列內的類型定義),我已經宣佈運營商即使< <(請求IT) 作爲數組結構的朋友?
謝謝!但我需要了解發生了什麼。我還編輯了:ostream&operator <<(ostream&os,const _Tarray&var)to:上面的ostream&operator <<(ostream&os,const數組&var)。 –
@OsagieOdigie默認情況下,如果沒有typename,編譯器會將該名稱視爲不是類型名稱。 –