Therefore, I am trying to write and read from a file using std::ostream_iteratorand std::iostream_iterator. The recording process works without errors. But as for reading, I'm lost. I have an error:
1> c: \ program files (x86) \ microsoft visual studio 14.0 \ vc \ include \ xutility (2316): error C2678: binary '=': operator not found that accepts a left operand of type 'const WRstruct' (or not acceptable conversion)
and he says that:
c: \ users \ xxxxxxx \ desktop \ ttttt \ ttttt \ wrstruct.h (21): note: maybe 'WRstruct & WRstruct :: operator = (const WRstruct &)' 1> c: \ program files (x86) \ microsoft visual studio 14.0 \ vc \ include \ xutility (2316): note: when trying to match the argument list '(const WRstruct, WRstruct)'
What is the correct way to overload operator=?
class:
#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;
}
Methods
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);
}
and main ():
#include <iostream>
#include "WRstruct.h"
int main()
{
WRstruct r;
r.write();
return 0;
}
source
share