问题
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')
回答1:
The compiler fails to see the operator overloads in your main.cpp
translation unit, because the overloads are not found in that file, nor are they found in any of the #include
files. You need to declare both overloads in your MyClass.h
file instead, after the MyClass
declaration:
MyClass.h:
#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;
};
istream& operator >>(istream &is, MyClass &cls);
ostream& operator <<(ostream &os, const MyClass &cls);
#endif /* MyClass_h */
You can leave the definitions as-is in your MyClass.cpp
file.
来源:https://stackoverflow.com/questions/42821684/using-cin-and-cout-to-populate-fields-of-a-class-c