运算符重载C ++; <<<<<<手术

时间:2013-04-30 03:18:43

标签: c++ operator-overloading

我在下面有一些代码,它们需要一些名字和年龄,并用它们做一些事情。最终会将它们打印出来。我需要使用全局print()更改operator<<函数。我看到on a different forum <<operator有两个参数,但是当我尝试它时,我得到一个“&lt;&lt;操作错误的参数太多了。有什么我做错了吗?我是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;
    }
};

2 个答案:

答案 0 :(得分:16)

您正在将<<运算符重载为成员函数,因此,第一个参数隐式地是调用对象。

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

重载为friend函数。

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

但是,规范的方法是将其作为free函数重载。您可以从以下帖子中找到非常好的信息:C++ operator overloading

答案 1 :(得分:2)

将运算符重载函数声明为朋友。

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