如何在课堂上使用指向ostream的指针

how to use pointer to ostream in class

本文关键字:ostream 指针 课堂      更新时间:2023-10-16

我需要类中的ostream指针,该指针将在构造类时创建。

我的代码是:

#include <iostream> 
#include <string> 
#include <vector> 
#include <map> 
#include <cstring> 
#include <climits> 
#include <cstdio> 
#include <fstream>
using namespace std; 
class test2_t {
    public:
        test2_t ()
        {
            std::filebuf fb;
            fb.open ("dump.txt",std::ios::out);
            ostream *output_ = new std::ostream(&fb);
        }
        virtual ~test2_t ()
        {}
        ostream *output_;
        void printing()
        {
            print(output_);
        }
        void print(ostream *out)
        {
            *out<<"dump data"<<"n";
        }
    private:
        /* data */
};
int main( )
{
    test2_t obj;
    obj.printing();
}

但是得到Segmentation fault我不知道为什么。请帮帮我。

您在代码中犯了以下错误:您在构造函数中"重新声明"了您的"Output"变量,因此指针ios仅存储在构造函数范围内的局部变量中。

更改此行:ostream*output=新std::ostream(&fb);into:*output_=新std::ostream(&fb);

通过这种方式,类的成员变量将填充correkt指针。

您可以按照如下方式更改构造器函数以使其工作:

    test2_t () : output_(new std::ofstream("dump.txt")) {            
    }

不要忘记释放析构函数中的资源:

    virtual ~test2_t () {
        delete output_;
    }