gpt4 book ai didi

c++ - 二元重载运算符=

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:07:32 25 4
gpt4 key购买 nike

所以我尝试使用 std::ostream_iteratorstd::iostream_iterator 写入和读取文件。写作过程很好,没有任何错误。但至于阅读,我迷路了。我的错误是:

1>c:\program files (x86)\microsoft visual studio 14.0\vc\include\xutility(2316): error C2678: binary '=': no operator found which takes a left-hand operand of type 'const WRstruct' (or there is no acceptable conversion)

它说:

c:\users\xxxxxxx\desktop\ttttt\ttttt\wrstruct.h(21): note: could be 'WRstruct &WRstruct::operator =(const WRstruct &)' 1> c:\program files (x86)\microsoft visual studio 14.0\vc\include\xutility(2316): note: while trying to match the argument list '(const WRstruct, WRstruct)'

重载operator=的正确方法是什么?

类别:

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <iterator>
#include <istream>

class WRstruct
{
private:
std::string name;
std::string number;
friend std::ostream& operator<<(std::ostream&, const WRstruct&);
friend std::istream& operator >> ( std::istream& is, WRstruct&);

public:
WRstruct(){};
void write();
void read();
~WRstruct(){};
};
std::ostream& operator<<(std::ostream& os, const WRstruct& p)
{
os << "User Name: " << p.name << std::endl
<< "Name: " << p.number << std::endl
<< std::endl;
return os;
}

std::istream& operator >> (std::istream& is, WRstruct& p)
{

is >> p.name>>p.number;
return is;
}

方法:

void WRstruct::write()
{
std::vector<WRstruct> vecP;
std::copy(std::istream_iterator<WRstruct>(std::cin),
std::istream_iterator<WRstruct>(), std::back_inserter(vecP));
std::ofstream temp("temp.txt", std::ios::out);
std::ostream_iterator<WRstruct>temp_itr(temp, "\n");
std::copy(vecP.begin(), vecP.end(), temp_itr);

}

void WRstruct::read()
{
std::vector<WRstruct> vec;

std::ifstream readFile("temp.txt");
std::istream_iterator<WRstruct> istr(readFile);
copy(vec.begin(), vec.end(), istr);

std::istream_iterator<WRstruct> end_istr;
copy(istr, end_istr, back_inserter(vec));

std::ostream_iterator<WRstruct> osIter(std::cout," ");
copy(vec.begin(),vec.end(),osIter);

}

和主要():

#include <iostream>
#include "WRstruct.h"

int main()
{
WRstruct r;
r.write();
//r.read();

return 0;
}

最佳答案

据我了解,您的函数 WRstruct::read 的含义是“从‘temp.txt’读取所有数据并将其写入控制台”。 顺便说一句,函数 read 打印一些东西很奇怪,因此请考虑相应地命名您的函数。

要使用 istream_iterator 从文件中读取内容,您应该创建一对迭代器(一个指向文件的开头,另一个指向空)并使用 std::copy。因此,函数的读取部分应该如下所示

std::vector<WRstruct> vec;

std::ifstream readFile("temp.txt");
std::istream_iterator<WRstruct> istr(readFile);
std::istream_iterator<WRstruct> end_istr;
copy(istr, end_istr, back_inserter(vec));

因此,您只需注释或删除 WRstruct::read 中的一行即可消除编译错误。

关于c++ - 二元重载运算符=,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44803215/

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