简体   繁体   中英

How to pass a class/object through constructor in C++

I want to make a wrapper Filer class to work with fstream library.

Thus, I want to pass an instance of fstream class through constructor of my own Filer class, which led to this code:

Filer::Filer(fstream fileObject)
{
    fileObject this->fileObj;
};

Though when I compile it, an error is thrown that :

1>Filer.cpp(10): error C2143: syntax error : missing ';' before 'this'

While when I do this:

Filer::Filer(fstream fileObject)
{
    this->fileObj = fileObject;
};

It throws this errors which complains that fstream could not be assigned in such way;

error C2679: binary '=' : no operator found which takes a right-hand operand of type 'std::fstream' (or there is no acceptable conversion)

How should I then make my constructor accept an object of type fstream ?

What you've got there is not C++. Try this:

Filer::Filer(fstream& fileObject)
  : fileObj(fileObject)
{
}

That uses an "initialization list" to store a reference to fileObject which must be declared as a member of the class. And you must use references, because streams are not copyable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM