fehim kus
fehim kus

Reputation: 21

ofstream object as variable

I am trying to create multiple files according to a filename in cpp. Using ofstream for that, I could not achieve it for now.

I'd appreciate if anyone can help me with 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.

Upvotes: -3

Views: 71

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 597941

You can't use statements at class scope, only declarations.

In any case, you need to use a reference variable for what you are attempting, eg:

std::ofstream& document_type = situation ? text1 : text2;
document_type << "hello world" << "\n";

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409432

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.

Upvotes: 1

Related Questions