Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
129 views
in Technique[技术] by (71.8m points)

c++ - Making operator<< virtual?

I need to use a virtual << operator. However, when I try to write:

virtual friend ostream & operator<<(ostream& os,const Advertising& add);

I get the compiler error

Error 1 error C2575: 'operator <<' : only member functions and bases can be virtual

How can I turn this operator virtual?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem with this setup is that the operator<< you defined above is a free function, which can't be virtual (it has no receiver object). In order to make the function virtual, it must be defined as a member of some class, which is problematic here because if you define operator<< as a member of a class then the operands will be in the wrong order:

class MyClass {
public:
    virtual ostream& operator<< (ostream& out) const;
};

means that

MyClass myObject;
cout << myObject;

will not compile, but

MyClass myObject;
myObject << cout;

will be legal.

To fix this, you can apply the Fundamental Theorem of Software Engineering - any problem can be solved by adding another layer of indirection. Rather than making operator<< virtual, consider adding a new virtual function to the class that looks like this:

class MyClass {
public:
    virtual void print(ostream& where) const;
};

Then, define operator<< as

ostream& operator<< (ostream& out, const MyClass& mc) {
    mc.print(out);
    return out;
}

This way, the operator<< free function has the right parameter order, but the behavior of operator<< can be customized in subclasses.

Hope this helps!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...