Help with ostream operator

In my program I have defined the ostream and am trying to have it call a function that already formatted the output, but it is not working. The error I get is: error: no match for 'operator<<' in 'os << (&duration)->Duration::asString()'

Here is the defined ostream:
1
2
3
4
ostream &operator <<(ostream &os, const Duration &duration)
{    os << duration.asString();
    return os;
}


Here is the defined asString() function:
1
2
3
4
void Duration::asString() const
{
    cout << days << ":" << hours << ":" << minutes << ":" << seconds << ":" << ticks;
}


Any help would be appreciated. The code works if I simply erase the asString fucntion and put the code from that directly into the ostream definition but that is not what my instructor is looking for. Thanks.
os << duration.asString(); You are trying to output result of .asString() function.
void Duration::asString() But it does not return anything.

Your asString function is strang. From its name I would ex[ect that it should return string, but instead it outputs to std::cout.
Your Duration::asString() function returns void and does the printing internally.
So it does not make sense to feed it to os as in: os << duration.asString();

You should do the printing directly in operator<<, that's the usual way of doing things:
http://www.parashift.com/c++-faq/output-operator.html

pepstein wrote:
The code works if I simply erase the asString fucntion and put the code from that directly into the ostream definition but that is not what my instructor is looking for.

What is your instructor looking for? Does he want you to create an std::string instead of just printing?

If so, your Duration::asString() must return an std::string, and for simplicity std::stringstream will be used to create the actual string. (Looking at your current code this is probably the goal.)

1
2
3
4
5
6
7
8
9
10
11
12
#include <sstream>
#include <string>

// ...

std::string Duration::asString() const
{
    std::stringstream ss;

    ss << days << ":" << hours << ":" << minutes << ":" << seconds << ":" << ticks;
    return ss.str();
}


Then your operator<< works unchanged as:

1
2
3
4
ostream &operator <<(ostream &os, const Duration &duration)
{    os << duration.asString();
    return os;
}

Last edited on
your Duration::asString() method doesn't return a value so you are basically doing this os << void which makes no sense.
I was having trouble figuring out how to return the string correctly, since you can't just do: string output = days << ":" << hours << ":" << minutes << ":" << seconds << ":" << ticks;

That's why I did it that way; you're right about what you said.
Ha, you guys are good, I forgot about stringstream. That fixed it, thanks.
Topic archived. No new replies allowed.