我想使用文件流和consol输出流。在构造函数中,我想根据传递给构造函数的参数初始化文件或consol输出流。然后我将在类中有另一个函数,它将输出重定向到该流。它的代码是什么?我正在尝试下面的代码,这是无效的。 欢迎任何其他设计建议。
class Test
{
private:
std::ios *obj;
std::ofstream file;
std::ostream cout1;
public:
// Test(){}
Test(char choice[])
{
if(choice=="file")
{
obj=new ofstream();
obj->open("temp.txt");
}
else
obj=new ostream();
}
void printarray()
{
for(int i=0;i<5;i++)
(*obj)<<"\n \n"<<"HI"
}
};
答案 0 :(得分:2)
这样的事情应该有效:
#include <iostream>
#include <fstream>
#include <string>
class Test
{
private:
std::ofstream file;
std::ostream& obj;
public:
// Use overloaded constructors. When the default constructor is used,
// use std::cout. When the constructor with string is used, use the argument
// as the file to write to.
Test() : obj(std::cout) {}
Test(std::string const& f) : file(f.c_str()), obj(file) {}
void printarray()
{
for(int i=0;i<5;i++)
obj<<"\n " << "HI" << " \n";
}
};
int main()
{
Test a;
a.printarray();
Test b("out.txt");
b.printarray();
}
PS 查看printarray
的更改。您使用%s
尝试的内容适用于printf
函数系列,但不适用于std::ostream
。
答案 1 :(得分:1)
欢迎任何其他设计建议。
其中两个成员没用:
std::ios *obj;
std::ofstream file;
std::ostream cout1;
您无法对std::ios
执行任何操作,与std::ostream
无关联的streambuf
无效,您永远不会使用file
或者cout1
无论如何!
你想:
std::ofstream file;
std::ostream& out;
如R Sahu的回答所示,并写信给out
。
Test(char choice[])
{
if(choice=="file")
这不起作用,您需要使用strcmp
来比较char
个字符串。您应该使用std::string
而不是char*
。