2013-11-15 58 views
2

我試圖使用運算符< <來輸出屬於我的類的私有成員的向量。如何超載<<運算符輸出作爲類成員的向量

編譯器不會讓我直接訪問矢量,因爲它們是私有的,但它也不會讓我訪問返回矢量的公共成員函數。

如何使< <運算符輸出私有成員矢量的所有內容?

這是我的課:

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; 
      } 

} 

回答

1

return os<< n.Names(); //won't let me access 

不起作用,因爲你想在一次寫整向量,而不是它的元素,ostream不提供針對std::vector超載operator <<。解決方案只是寫入vector的元素,這是由此函數返回的。

for(int i=0;i<n.Names().size();i++) 
    cout << n.Names()[i]; 

作爲一個方面說明:你可能不希望與大載體使用的版本,因爲(除非你的編譯器是足夠聰明,使函數內聯),會消耗大量的時間,返回整個向量。嘗試將常量引用返回給向量,而不是向量本身。

2

n.Names()返回一個向量,不能直接通過標準的operator <<方法打印向量。您必須遍歷該矢量並打印其元素。

std::ostream& operator<<(std::ostream& os, const Name_pairs& n) 
{ 
    if (!os.good()) 
     return os; 

    auto names = n.Names(); 
    std::copy(names.begin(), names.end(), 
          std::ostream_iterator<std::string>(os)); 
    return os; 
} 
+0

std :: ostream_iterator (os));當我把這段代碼放到我的<<函數中時,編譯器給我的錯誤是告訴「std沒有成員iostream_interator」。您的答案是否表明,對於<<運算符來處理矢量,矢量必須被複制到「os」對象中?有沒有其他方法? – user2904033

+0

@ user2904033包含''和''標題。 – 0x499602D2