操作员过载C++;<<操作的参数过多
Operator Overloading C++; too many parameters for << operation
下面有一些代码,将获取一些姓名和年龄,并对它们进行一些处理。最终它会把它们打印出来。我需要用全局的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;
}
相关文章:
- 如何反转整数参数包
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用默认参数等选择模板专业化
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 函数调用中参数的顺序重要吗
- 部分定义/别名模板模板参数
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- 使用不带参数的函数访问结构元素
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 如何使用Luacneneneba API正确读取字符串和表参数
- 在派生函数中指定void*参数
- 视图中的参数推导失败:take_while
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 左角支架解释为操作员&lt;而不是模板参数
- 重载运算符<<:此运算符函数的参数太多
- 重载<<运算符错误C2804:二进制'运算符<<'参数太多