lundi 31 août 2015

Overriding << operator in C++11, pure virtual in base class and different implementations in each derived class

I have a given base class that has some implementations, and has two derived classes. I want to override the cout operator << to have a custom way to print the data I want from these classes, and each of the derived classes does so slightly differently.

class Base
{
public:
    // Various functions, as expected
    virtual friend std::ostream& operator<<(std::ostream& stream, const Base& base) = 0;
    // More functions, members, all those things
}

These are the implementations in the derived classes:

class DerivedOne
{
public:
    std::ostream& operator<<(std::ostream& stream, const Base& base)
    {
    stream << base._someData << "\t" << "first desired print statement: "  << base._otherData;
    }

class DerivedTwo
{
public:
    std::ostream& operator<<(std::ostream& stream, const Base& base)
    {
    stream << base._someData << "\t" << "second desired print statement: "  << base._otherData;
    }

Note that the actual class members I'm calling belong to the Base class, and don't vary between the two implementations. The only thing that changes is the string between the data members.

This is the compilation error I get on Visual Studio. It seems one of the problems is that the << operator specifically appears with the keyword "friend," which makes it more complicated than other operators.

One of the ways I thought to solve this problem is to simple save each string as part of base._otherData (which is also a string), but that seems inelegant to me, and I was hoping that there was a more direct way to override this operator and have varying implementations in my derived classes.

[I would just like to add as a side note that I'm relatively new to this site, and while I tried to format and phrase the question properly, I'm sure there are some mistakes, and I appreciate any constructive feedback and editing of style.]

Aucun commentaire:

Enregistrer un commentaire