发送到 c++ 中的文件

Sending to files in c++

本文关键字:文件 c++      更新时间:2023-10-16

我已经写了folowign多态类。

 #include <iostream>
 #include <fstream>
 using namespace std;
 class SaveAndDraw
 {
    public:
      virtual void draw()=0;
      void saveToFile();
 };
 class MakeShape : public SaveAndDraw
 {
   public:
      virtual void draw();
 };
 void SaveAndDraw::saveToFile();
 {

如何将虚拟绘制函数保存到 txt 文件?

 } 
 void MakeShape::draw()
 {
    for(int i = 0; i < 10 ; i++)
    {
        for(int j = 0; j < i; j++)
        {
            cout << "*";
        }
        cout << endl;
    }
}
int main()
{
    SaveAndDraw *creation = new MakeShape;
    creation->draw();
    creation->saveToFile();
    delete creation;
    return 0;
}

我不知道如何将绘图保存到文件中。我知道要创建您必须说的文件

fstream fout;
fout.open("test.txt");
fout.close();

不要在绘制函数中写入 std::cout,而是将其传递fout .

void MakeShape::draw(std::ostream & out)
 {
    for(int i = 0; i < 10 ; i++)
    {
        for(int j = 0; j < i; j++)
        {
            out << "*";
        }
        out << endl;
    }
}

如果您需要绘制以写入 cout,只需将其作为参数传递即可。
这样,您就不再需要保存到文件功能了。