操作员过载C++;<<操作的参数过多

Operator Overloading C++; too many parameters for << operation

本文关键字:lt 参数 操作 操作员 C++      更新时间:2023-10-16

下面有一些代码,将获取一些姓名和年龄,并对它们进行一些处理。最终它会把它们打印出来。我需要用全局的operator<<来改变我的print()函数。我在不同的论坛上看到<<operator需要两个参数,但当我尝试它时,我得到了"参数太多<<"操作错误。我做错了什么吗?我是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;
    }
};

您将<<操作符重载为成员函数,因此,第一个参数是隐式调用对象。

您应该将其重载为friend函数或作为自由函数。例如:

重载为friend函数

friend ostream& operator<<(ostream& out, int x){
     out << names[x] << " " << ages[x] <<endl;
     return out;
}
然而,规范的方法是将其重载为free函数。c++操作符重载

声明操作符重载函数为友元。

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