2013-04-30 32 views
7

Tôi có một số mã bên dưới sẽ lấy một số tên và tuổi và làm một số nội dung với chúng. Cuối cùng nó sẽ in ra. Tôi cần thay đổi chức năng print() của mình bằng một số operator<< toàn cầu. Tôi thấy on a different forum rằng <<operator có hai tham số, nhưng khi tôi thử, tôi nhận được một "quá nhiều thông số cho lỗi hoạt động < <. Có điều gì tôi đang làm không? Tôi mới hơn với C++ và tôi thực sự không có được điểm của toán tử quá tải.Quá tải nhà khai thác C++; quá nhiều tham số cho << hoạt động

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

Trả lời

12

Bạn đang quá tải << điều hành như một hàm thành viên, do đó, tham số đầu tiên là mặc nhiên các đối tượng gọi điện thoại.

Bạn nên hoặc quá tải nó như friend chức năng hoặc như một chức năng miễn phí. Ví dụ :

quá tải với chức năng friend.

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

Tuy nhiên, cách kinh điển là quá tải như chức năng free. Bạn có thể tìm thấy thông tin rất tốt từ bài đăng này: 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; 
} 
Các vấn đề liên quan