Home >Backend Development >C++ >How Can You Implement a Virtual `operator
Overcoming the Virtual Operator<< Conundrum
In an attempt to implement a virtual << operator, the following code results in a compiler error:
<code class="cpp">virtual friend ostream & operator<<(ostream& os,const Advertising& add);</code>
The Root of the Issue
The defined operator<< is a free function, disabling its qualification as virtual due to the absence of a receiver object. To achieve the desired virtual functionality, the operator needs to be defined as a class member.
The Problem with Direct Definition
Defining operator<< as a class member poses a different issue. The operands will be reversed, causing complications when attempting to output an object:
<code class="cpp">MyClass myObject; myObject << cout; // Legal but not our intended usage</code>
The Solution: Indirect Approach
To navigate these challenges, introduce an additional virtual function:
<code class="cpp">class MyClass { public: virtual void print(ostream& where) const; };</code>
Then, redefine operator<< as a free function, leveraging the new virtual function:
<code class="cpp">ostream& operator<< (ostream& out, const MyClass& mc) { mc.print(out); return out; }</code>
This setup allows the operator<< free function to maintain the correct parameter order while enabling customization of the output behavior in subclasses through the print() function.
The above is the detailed content of How Can You Implement a Virtual `operator. For more information, please follow other related articles on the PHP Chinese website!