gpt4 book ai didi

C++ 重载 ostream 和 istream 运算符

转载 作者:行者123 更新时间:2023-11-30 04:43:16 24 4
gpt4 key购买 nike

此代码的目的是读取包含名称、十亿美元和国家的文件,这些文件由制表符分隔。我需要创建一个 Billionaire 类并重载 ostream 和 istream 运算符以方便将文件读入 vector 并将内容写入输出。然后创建一个映射,将国家字符串映射到一对。该对包含第一个的拷贝名单中每个国家的亿万富翁和计算每个国家亿万富翁人数的计数器国家。但是,我不能重载流和流运算符。

我试图在 Billionaire 类中重载这些运算符,但我以错误告终。

#include <iostream>
#include <vector>
#include <utility>
#include <algorithm>
#include <set>
#include <map>
#include <string>
#include <iterator>
#include <fstream>
#include <istream>
#include <ostream>

using namespace std;

class Billionaire{
//overload the ostream and istream operators to conveniently
//read the file into a vector and write the content to the output

public :

friend ostream &operator<<(ostream &stream, Billionaire o);
friend istream &operator>>(istream &stream, Billionaire &o);
};

int main(){

std::ifstream stream("Forbes2018.txt");

if(!stream){

cout << " WARNING : File not found !" << endl ;

}

vector <Billionaire> billionaires;
copy (istream_iterator<Billionaire>( stream ),
istream_iterator<Billionaire>() , back_inserter( billionaires ));
copy (billionaires.begin () , billionaires.end () ,
ostream_iterator < Billionaire >( cout , "\n"));

map < string , pair < const Billionaire , size_t >> m;

}

我有 2 个错误::-1: 错误: 找不到体系结构 x86_64 的符号:-1: 错误:链接器命令失败,退出代码为 1(使用 -v 查看调用)

最佳答案

你的重载尝试是一个好的开始:你已经向编译器宣布将有一个重载:

friend ostream &operator<<(ostream &stream, Billionaire o);
friend istream &operator>>(istream &stream, Billionaire &o);

不幸的是,有些东西不见了。这就是链接器消息所说的。您仍然需要告诉编译器如何这个重载看起来像:

ostream &operator<<(ostream &stream, Billionaire o) {
// put your code here
...
return stream;
}
istream &operator>>(istream &stream, Billionaire &o) {
// put your code here
...
return stream;
}

如果您在 Billionaire 中定义了这些运算符,编译器将无法在这里使用它们:在 main 中您调用独立运算符(您已声明为 friend ),而您会定义必须在 Billionaire 上使用 .-> 运算符调用的类成员,并且具有与您不同的签名在 main 中重新使用。

关于C++ 重载 ostream 和 istream 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58361408/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com