2013-04-30 67 views
7

Aşağıda bazı isimler ve yaşlar alacak ve onlarla bazı şeyler yapacak bazı kod var. Sonunda onları basacaktır. print() işlevini global bir operator<< ile değiştirmem gerekiyor. on a different forum'u <<operator'un iki parametre aldığını gördüm, ancak denediğimde "< < işlem hatası için çok fazla parametre alıyorum. Yanlış yaptığım bir şey var mı? C++ 'ya daha yeni geliyorum ve gerçekten operatör noktasını alamıyorum bir üye fonksiyonu olarak << operatörü aşırı yükleniyor aşırı yükleme.Operatör Aşırı Yüklemesi C++; << operasyon için çok fazla parametre

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

cevap

12

, bu nedenle, ilk parametre örtülü olarak çağıran nesnedir.

Sen friend fonksiyonu olarak veya serbest fonksiyonu olarak aşırı gelmelidir. Örneğin :

friend işlevi gibi aşırı yükleme.

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

Bununla birlikte, standart bir şekilde free fonksiyonu olarak aşırı etmektir. Bu gönderiden çok iyi bilgileri bulabilirsiniz: 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; 
} 
İlgili konular