使用cin>>和cout<<填充类C ++的字段 [英] Using cin >> and cout << to populate fields of a class C++

查看:114
本文介绍了使用cin>>和cout<<填充类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&gt;&gt;和cout&lt;&lt;填充类C ++的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆