I am trying to create multiple file according to filename in cpp. Using ofstream for that and could not achieve for now. Appreciate if anyone help me about that.
I am writing down here
static std::ofstream text1;
static std::ofstream text2;
class trial{
public:
if(situation == true) {
document_type = text1;
}
if(situation == false) {
document_type = text2;
}
document_type << "hello world" << "\n";
}
ofstream object as variable
CodePudding user response:
Assignment copies the objects, and it's not possible to create copies of streams. You can only have reference to streams, and you can't reassign references.
Instead I suggest you pass a reference to the wanted stream to the trial
constructor instead, and store the reference in the object:
struct trial
{
trial(std::ostream& output)
: output_{ output }
{
}
void function()
{
output_ << "Hello!\n";
}
std::ostream& output_;
};
int main()
{
bool condition = ...; // TODO: Actual condition
trial trial_object(condition ? text1 : text2);
trial_object.function();
}
Also note that I use plain std::ostream
in the class, which allows you to use any output stream, not only files.