I have a class in MyClass.h
defined like this:
#ifndef MyClass_h
#define MyClass_h
#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;
class MyClass {
public:
string input
void ReadFrom(istream &is);
void WriteTo(ostream &os) const;
};
#endif /* MyClass_h */
MyClass.cpp
looks like this:
#include <stdio.h>
#include <string>
#include <iostream>
#include "MyClass.h"
using namespace std;
void MyClass::ReadFrom(istream &is) {
// put data into member 'input'
}
void MyClass::WriteTo(ostream &os) const {
// output data in member 'input'
}
istream& operator >>(istream &is, MyClass &cls) {
cls.ReadFrom(is);
return is;
}
ostream& operator <<(ostream &os, const MyClass &cls) {
cls.WriteTo(os);
return os;
}
main.cpp
looks like this:
#include <stdio.h>
#include <string>
#include <iostream>
#include "MyClass.h"
using namespace std;
int main(int argc, const char * argv[]) {
MyClass c;
std::cout << "Enter some input" << endl;
std::cin >> c;
return 0;
}
What I am trying to accomplish is to override the >>
and <<
operators so that std::cin
can simply read data into the class member(s), and then std::cout
can spit out all of the data in those members.
I do not want to use friend
functions.
Right now, I am getting an error around the std::cin >> c;
line that says:
Invalid operands to binary expression ('istream' (aka 'basic_istream<char>') and 'MyClass')