2013-04-30 14 views
7

के लिए बहुत सारे पैरामीटर मेरे पास कुछ कोड है जो कुछ नाम और उम्र लेगा और उनके साथ कुछ सामान करेगा। आखिरकार यह उन्हें प्रिंट करेगा। मुझे अपने print() फ़ंक्शन को वैश्विक operator<< के साथ बदलने की आवश्यकता है। मैंने on a different forum देखा है कि <<operator दो पैरामीटर लेता है, लेकिन जब मैं इसे आज़माता हूं तो मुझे < < ऑपरेशन त्रुटि के लिए बहुत अधिक पैरामीटर मिलते हैं। क्या कुछ गलत है? मैं सी ++ के लिए नया हूं और मुझे वास्तव में ऑपरेटर का बिंदु नहीं मिलता है ओवरलोडिंग।ऑपरेटर ओवरलोडिंग सी ++; << ऑपरेशन

#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; 
} 
संबंधित मुद्दे