问题
I've got function. If user didn't provide ofstream
element into this function:
bool isPolpierwsza(int, bool = false, ofstream = NULL);
than I want to asign "plik"
bool isPolpierwsza(int liczba, bool wypisz, ofstream plik)
to NULL
value.
My compiler put error:
2.9.cpp:5:48: error: no viable conversion from 'long' to 'ofstream' (aka 'basic_ofstream')
bool isPolpierwsza(int, bool = false, ofstream = NULL);
How to setup default value to ofstream to be treated like NULL
or "false"?
回答1:
You can use two overloads, one of which doesn't take the std::ofstream
argument:
bool isPolpierwsza(int liczba, bool wypisz)
{
return isPolpierwsza(liczba, wypisz, /* your own argument */);
}
回答2:
You could pass the stream buffer instead:
bool isPolpierwsza(int, bool = false, std::streambuf* osbuf = nullptr)
{
std::ostream os(osbuf? osbuf : std::cout.rdbuf());
os << "yay it works\n";
return false;
}
Now, call it like this:
std::ofstream ofs("myoutput.txt");
bool result = isPolpierwsza(42, true, ofs.rdbuf());
Or indeed, without the parameter.
回答3:
First of all, it may be useful to use ostream instead of ofstream, as this is more general and considered better practice.
Then, you can simply assign 'cout' instead of 'NULL'. NULL doesn't work because ostream is not a pointer but a struct. This means the struct has to be filled out completely and can not be assigned NULL. Instead, you could use cout, like
bool isPolpierwsza(int, bool = false, ostream& = cout);
来源:https://stackoverflow.com/questions/19469462/default-ofstream-class-argument-in-function