如何在课堂上使用指向ostream的指针
how to use pointer to ostream in class
我需要类中的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_;
}
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么使用 "this" 指针调用派生成员函数?
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用指针从C++中的数组中获取最大值
- 助记符和指向成员语法的指针
- 嵌入方指针压缩已禁用
- 重载 ostream << 运算符,指针作为参数,导致输出上的内存地址
- Ostream操作员Strangley不接受我的堆栈指针
- 无法使用 istream 和 ostream 指针跨 Linux 管道写入
- 使用指针数组中的对象调用重载的友元 ostream 插入运算符将返回内存地址
- 没有合适的默认构造函数可用于初始化 ostream 指针
- C++:无法在ostream和运算符<<中创建节点指针
- 正在获取ostream模板以打印指针列表中的实例属性
- 地址和指针的 ostream 运算符<<
- 为什么即使我没有使用 ostream 对象,ostream 的 put 指针也会被修改
- 如何获得std::ostream的指针.编写序列化
- 如何在课堂上使用指向ostream的指针
- istream >> ostream << 运算符重载与 * 指针
- 将指向 istream 和 ostream 的指针存储在类C++中