使用cin>>和cout<<填充类C ++的字段 [英] Using cin >> and cout << to populate fields of a class C++
问题描述
我在MyClass.h
中有一个这样定义的类:
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
看起来像这样:
#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
看起来像这样:
#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;
}
我要完成的工作是覆盖>>
和<<
运算符,以便std::cin
可以简单地将数据读取到类成员中,然后std::cout
可以吐出所有数据在那些成员中.
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.
我不想使用friend
函数.
现在,我在std::cin >> c;
行上看到一条错误消息:
Right now, I am getting an error around the std::cin >> c;
line that says:
对二进制表达式("istream"(又名"basic_istream< char>"和"MyClass")无效的操作数
Invalid operands to binary expression ('istream' (aka 'basic_istream<char>') and 'MyClass')
推荐答案
编译器无法在main.cpp
转换单元中看到运算符重载,因为在该文件中找不到重载,也没有在任何文件中找到重载. #include
文件.您需要在MyClass
声明之后在MyClass.h
文件中声明两个重载:
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:
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 */
您可以将定义保留在MyClass.cpp
文件中.
You can leave the definitions as-is in your MyClass.cpp
file.
这篇关于使用cin>>和cout<<填充类C ++的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!