含有类、动态分配内存、插入和提取运算符重载、文件读写的程序示例

程序说明

  1. 在类当中定义提取和插入运算符重载,并对参数分别进行检测,如果是输入或输出对象则进行额外处理。
  2. 在写文件时需要写入字符串的长度,但输出不需要。读文件时需要读取字符串的长度,但输入不需要。
  3. 为了简化步骤,输入时控制了字符串的长度,否则可以用链表等不定长的容器来获取输入。
  4. 出于简化问题的角度,本程序把保存数据用的文件名固定了,因此如果创建需要多个对象(包括复制构造函数和赋值运算符等)时可能会出现问题(会导致数据的覆盖等)。
#include <iostream>
#include <fstream>
using namespace std;

class rect;
istream& operator >>(istream & is , rect & r);
ostream& operator <<(ostream & os , const rect & r);

class rect
{
    int left , top , right , bottom;
    char *info;
public:
    rect()
    {
        ifstream infile("rect.txt");
        if(infile)
        {
            infile >> *this;
            infile.close();
        }
        else
            cin >> *this;
    }
    ~rect()
    {
        ofstream outfile("rect.txt");
        outfile << *this;
        outfile.close();
        delete []info;
    }
    friend istream& operator >>(istream & is , rect & r)
    {
        int len;
        if(&is == &cin)
        {
            char c[20];
            cout << "请输入矩形的四个坐标:";
            cin >> r.left >> r.top >> r.right >> r.bottom;
            cin.get();
            cout << "请输入矩形的描述(20字符以内):";
            cin.getline(c , 20);
            len = strlen(c);
            r.info = new char[len + 1];
            strcpy(r.info , c);
        }
        else
        {
            is >> r.left >> r.top >> r.right >> r.bottom >> len;
            r.info = new char[len + 1];
            is.get();
            is.getline(r.info , len + 1);
        }
        return is;
    }
    friend ostream& operator <<(ostream & os , rect & r)
    {
        os << r.left << ' ' << r.top << ' ' << r.right << ' ' << r.bottom << endl;
        if(&os != &cout)
            os << strlen(r.info) << endl;
        return os << r.info << endl;
    }
};
int main()
{
    rect r;
    cout << r;
    return 0;
}

Leave a Comment

电子邮件地址不会被公开。 必填项已用*标注