Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/135.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 我可以通过std::ostream&;对于预期std::of流的函数_C++ - Fatal编程技术网

C++ 我可以通过std::ostream&;对于预期std::of流的函数

C++ 我可以通过std::ostream&;对于预期std::of流的函数,c++,C++,我想做的是: 我想将错误消息erither重定向到std::cerr或文件 取决于命令行参数。如果没有提供日志文件,则程序应在屏幕上输出错误消息。 我的做法如下: class A { void SetLogFileStream(T& err_outstream); }; //main.cpp A a; std::string filename; T1* t1; if(argc>2) { filename = argv[1]; //if provided by c

我想做的是: 我想将错误消息erither重定向到std::cerr或文件 取决于
命令行
参数。如果没有提供日志文件,则程序应在屏幕上输出错误消息。 我的做法如下:

class A {

    void SetLogFileStream(T& err_outstream);
};
//main.cpp

A a;
std::string filename;
T1* t1;
if(argc>2) {
    filename = argv[1]; //if provided by command line 

    std::ofstream fp(filename);
    t1 = &fp;

}
else {

    std::ostream* err_outstream = &std::cerr;
    t1 = err_outstream;
}

a.SetLogFileStream(t1);
函数的参数类型应该是什么
SetLogFileStream
或类型
T1

这样我就可以传递一个指向文件或
std::cerr

否的指针。但事实正好相反。您可以将
std::ofstream
传递给需要
std::ostream&
的函数,或将
std::ofstream*
传递给需要
std::ostream*
的函数。因此,函数应该接受std::ostreamref或指针。

类型应该是std::ostream。因为函数参数是引用,而参数是指针,所以它不能完全按照您编写的代码工作。但是,如果解决了这个问题(无论哪种方法),它都会起作用。

将该方法声明为:

class A {
    void SetLogStream(std::ostream& err_outstream);
};
您的代码有几个问题。打开的文件流超出范围并被销毁。您需要像这样修复它:

std::ofstream f; // <-- this have to remain in scope while you use it for 'a'
A a;

if(args > 2) {
    f.open(argv[1]);
    a.SetLogStream(f);
} else {
    a.SetLogStream(cerr);
}
流f的标准::;//2) { f、 开放(argv[1]); a、 SetLogStream(f); }否则{ a、 SetLogStream(cerr); }