2013-04-30 121 views
7

我在下面有一些代碼,需要一些名稱和年齡,並與他們做一些事情。最終它將打印出來。我需要改變我的print()功能與全球operator<<。我看到on a different forum<<operator需要兩個參數,但是當我嘗試它時,我得到一個「太多參數< <操作錯誤。是否有什麼我做錯了?我更新C++,我真的沒有得到操作點重載。運算符重載C++; <<操作的參數太多

#include <iostream>; 
#include <string>; 
#include <vector>; 
#include <string.h>; 
#include <fstream>; 
#include <algorithm>; 

using namespace::std; 

class Name_Pairs{ 
    vector<string> names; 
    vector<double> ages; 

public: 
    void read_Names(/*string file*/){ 
     ifstream stream; 
     string name; 

     //Open new file 
     stream.open("names.txt"); 
     //Read file 
     while(getline(stream, name)){ 
      //Push 
      names.push_back(name); 
     } 
     //Close 
     stream.close(); 
    } 

    void read_Ages(){ 
     double age; 
     //Prompt user for each age 
     for(int x = 0; x < names.size(); x++) 
     { 
      cout << "How old is " + names[x] + "? "; 
      cin >> age; 
      cout<<endl; 
      //Push 
      ages.push_back(age); 
     } 

    } 

    bool sortNames(){ 
     int size = names.size(); 
     string tName; 
     //Somethine went wrong 
     if(size < 1) return false; 
     //Temp 
     vector<string> temp = names; 
     vector<double> tempA = ages; 
     //Sort Names 
     sort(names.begin(), names.end()); 

     //High on performance, but ok for small amounts of data 
     for (int x = 0; x < size; x++){ 
      tName = names[x]; 
      for (int y = 0; y < size; y++){ 
       //If the names are the same, then swap 
       if (temp[y] == names[x]){ 
        ages[x] = tempA[y]; 
       } 
      } 
     } 
    } 

    void print(){ 
     for(int x = 0; x < names.size(); x++){ 
      cout << names[x] << " " << ages[x] << endl; 
     } 
    } 

    ostream& operator<<(ostream& out, int x){ 
     return out << names[x] << " " << ages[x] <<endl; 
    } 
}; 

回答

12

您重載<<操作者作爲成員的功能,因此,第一個參數是隱式地調用對象。

你應該要麼過載它作爲friend函數或作爲遊離的功能。例如:

超載爲friend函數。

friend ostream& operator<<(ostream& out, int x){ 
    out << names[x] << " " << ages[x] <<endl; 
    return out; 
} 

但是,規範的方法是將其重載爲free函數。你可以從這篇文章中找到非常好的信息:C++ operator overloading

1
declare operator overloading function as friend. 

friend ostream& operator<<(ostream& out, int x) 
{ 
     out << names[x] << " " << ages[x] <<endl; 
     return out; 
}