我試圖使用運算符< <來輸出屬於我的類的私有成員的向量。如何超載<<運算符輸出作爲類成員的向量
編譯器不會讓我直接訪問矢量,因爲它們是私有的,但它也不會讓我訪問返回矢量的公共成員函數。
如何使< <運算符輸出私有成員矢量的所有內容?
這是我的課:
class Name_pairs
{
public:
Name_pairs (){}
//....
vector<string> Names (){return names; }
vector<double> Ages (){return ages; }
vector<double> Sorted_ages(){return sorted_ages;}
private:
//....
vector<string> names;
vector<double> ages;
vector<double> sorted_ages;
};
這是重載< <功能:
ostream& operator<<(ostream& os, const Name_pairs & n)
{
return os<< n.Names(); //won't let me access
return os<< n.names.size(); //won't let me access
}
這是我想通過重載< <功能更換打印功能:
void Name_pairs:: print_name_age ()
{
cout << endl << endl;
cout << "These names and ages are now sorted" << endl;
for(int index = 0; index < names.size(); ++index)
{
cout << "index " << index << ": " << names[index]<< " is age: " << sorted_ages[index] <<endl;
}
}
std :: ostream_iterator(os));當我把這段代碼放到我的<<函數中時,編譯器給我的錯誤是告訴「std沒有成員iostream_interator」。您的答案是否表明,對於<<運算符來處理矢量,矢量必須被複制到「os」對象中?有沒有其他方法? –
user2904033
@ user2904033包含''和''標題。 –
0x499602D2