繁体   English   中英

使用fstream将类对象写入文件,然后读取

[英]Writing a class object into a file using fstream and then read it

我想做一个学生班,接受3个输入信息,并输出这个文件。 这个怎么样 这是我的尝试:

#include <iostream>
using namespace std;
class Student{
  private:
    char name[50];
    char id[50];
    int age;
  public:
    void getdata()
    {
        //take name as input
        //take id as input
        //take age as input
    }
    void showdata()
    {
         //display stored file
    }
 }

int main()
{
    Student s1;
    ofstream s1("student.txt");      //i want to store that 's1' object
    //anything else
    return 0;
}

C ++使用流范例来实现标准输入/输出。

流范例意味着,如果您的应用程序要访问/使用资源(文件,控制台等),则流将充当您的应用程序和资源之间的中介者:

                     ofstream       +----+
              +-------------------->|File|
              |                     +----+
              |
       +------+------+
       | Application |
       +------+------+
              |
              |                     +-------+
              +-------------------->|Console|
                        cout        +-------+

这意味着你每次执行的读/写操作是真的流操作。 这样做的重点是,流操作基本上是相同的,而与所使用的资源类型(和流的类型)无关。

这使我们可以实现“通用”(通用含义对任何类型的流/资源均有效)。 怎么样? 重载C ++运算符>>和<<

对于输入操作(输入意味着从流中接收数据并将其放入我们的变量/对象中),我们需要重载>>运算符,如下所示:

istream& operator>>(istream& is , MyClass& object)
{
    is >> object.myClassAtributte; (1)
    ... //Same for every attribute of your class.

    return is;
}

首先,请注意输入流是通过引用传递的。 通过引用,因为流不可复制(复制流的确切含义是什么?复制应用程序和资源之间的链接?听起来很荒谬),并且非常量,因为您将要修改流(您将要编写通过它)。

最后,请注意该函数不会返回void,而是返回对传递给该函数的相同流的引用。 这样您就可以编写级联写入/读取的句子,例如cout << "Hello. " << "Im" << " Manu343726" << endl;

对于输出操作(输出意味着将数据发送到流),我们需要重载<<操作符,实现完全相同:

ostream& operator<<(ostream& os , const MyClass& object)
{
    os << object.myClassAtributte; (1)
    ... //Same for every attribute of your class.

    return os;
}

请注意,在这种情况下,您的对象会传递const,因为我们不会对其进行修改(我们只会读取其属性)。

(1)最好实现此功能,使其成为您班上的朋友,以使我们能够访问私有/受保护的成员。

您必须重载ostreamistream <<>>运算符

std::ostream& operator<< (std::ostream& stream, const Student& student)
std::istream& operator<< (std::istream& stream, Student& student)

让他们成为朋友并实施

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM