Home >Backend Development >C++ >How to Define a Virtual `
Overcoming Virtual << Operator Error
When attempting to define a virtual << operator as a free function, developers may encounter the compiler error "operator <<: only member functions and bases can be virtual." This error arises because free functions cannot be virtual.
To resolve this issue, consider adding an intermediary layer by introducing a new virtual member function within the class:
<code class="cpp">class MyClass { public: virtual void print(ostream& where) const; };</code>
This virtual function provides a means to customize the output behavior in subclasses.
Next, define the operator<< as a free function with the correct parameter order:
<code class="cpp">ostream& operator<< (ostream& out, const MyClass& mc) { mc.print(out); return out; }</code>
This approach ensures that the operator<< has the desired parameter order while allowing for the virtual behavior to be defined in the subclasses.
The above is the detailed content of How to Define a Virtual `. For more information, please follow other related articles on the PHP Chinese website!