【发布时间】:2011-06-23 16:37:24
【问题描述】:
我正在编写一个 C++ 程序,我需要一些帮助来理解错误。
默认情况下,我的程序会打印到终端 (STDOUT)。但是,如果用户提供文件名,程序将打印到该文件。如果我正在写入终端,我将使用 std::cout 对象,而如果我正在写入文件,我将创建并使用 std::ofstream 对象。
但是,我不想不断检查是否应该写入终端或文件。由于std::cout 和std::ofstream 对象都继承自std::ostream 类,我想我会创建一种接受std::ostream 对象的print_output 函数。在调用这个函数之前,我会检查我是否应该打印到一个文件。如果是这样,我将创建std::ofstream 对象并将其传递给打印函数。如果没有,我将简单地将std::cout 传递给打印函数。这样,打印函数就不必担心打印到哪里了。
我认为这是个好主意,但我无法编译代码。我在这里创建了一个过于简化的示例。这是代码...
#include <fstream>
#include <iostream>
#include <stdio.h>
void print_something(std::ostream outstream)
{
outstream << "All of the output is going here\n";
}
int main(int argc, char **argv)
{
if(argc > 1)
{
std::ofstream outfile(argv[1]);
print_something(outfile);
}
else
{
print_something(std::cout);
}
}
...这是编译时错误。
dhrasmus:Desktop standage$ g++ -Wall -O3 -o test test.c
/usr/include/c++/4.2.1/bits/ios_base.h: In copy constructor ‘std::basic_ios<char, std::char_traits<char> >::basic_ios(const std::basic_ios<char, std::char_traits<char> >&)’:
/usr/include/c++/4.2.1/bits/ios_base.h:779: error: ‘std::ios_base::ios_base(const std::ios_base&)’ is private
/usr/include/c++/4.2.1/iosfwd:55: error: within this context
/usr/include/c++/4.2.1/iosfwd: In copy constructor ‘std::basic_ostream<char, std::char_traits<char> >::basic_ostream(const std::basic_ostream<char, std::char_traits<char> >&)’:
/usr/include/c++/4.2.1/iosfwd:64: note: synthesized method ‘std::basic_ios<char, std::char_traits<char> >::basic_ios(const std::basic_ios<char, std::char_traits<char> >&)’ first required here
test.c: In function ‘int main(int, char**)’:
test.c:15: note: synthesized method ‘std::basic_ostream<char, std::char_traits<char> >::basic_ostream(const std::basic_ostream<char, std::char_traits<char> >&)’ first required here
test.c:15: error: initializing argument 1 of ‘void print_something(std::ostream)’
关于我为什么会收到这些错误的任何想法?是我编码错误,还是我的方法存在根本性错误?
谢谢!
【问题讨论】:
标签: c++ reference copy ostream ofstream