1
votes

I have opened a file to write to, and according to some conditions sometimes I want to print output to the screen and sometimes to the file. So I edited my function to be like this:

Cacl(const std::string &str, const ofstream &to=std::cout)

But I'm getting an error, what may cause this?

no viable conversion from 'std::__1::ostream' (aka 'basic_ostream<char>') to 'const std::__1::ofstream' (aka 'const basic_ofstream<char>')
void Calculator::solve(const std::string &command, const ofstream &to=std::cout) {
1

1 Answers

6
votes

std::cout is an object of type std::ostream which is a base class of std::ofstream (it's more general than std::ofstream), so you could just do:

void Calculator::solve(const std::string &str, std::ostream &to = std::cout) {
                             // instead of ofstream ^^^^^^^ 

and now you can pass an ofstream object to this function as well.

Also, the ostream shouldn't be const otherwise you won't be able to write to it.