Home >Backend Development >C++ >How to Implement Virtual Operator Overloading in C ?
In C , operators can be overloaded for custom data types, providing tailored behaviors. However, virtual methods, allowing for polymorphic behavior, cannot be directly used for operator overloading.
Consider the desire to create a virtual operator << to customize printing for a class Advertising. Attempts to define a virtual friend operator << result in a compiler error, stating that only member functions and bases can be virtual.
To circumvent this limitation, the operator << cannot be made virtual directly. Instead, a new virtual member function print can be added to the Advertising class. The << operator can then be redefined as a free function:
<code class="cpp">class Advertising { public: virtual void print(ostream& os) const; }; ostream& operator<< (ostream& os, const Advertising& add) { add.print(os); return os; }</code>
In this approach, the print member function can be overridden in subclasses to customize printing behavior, while the << operator maintains the correct parameter order for convenient use.
The above is the detailed content of How to Implement Virtual Operator Overloading in C ?. For more information, please follow other related articles on the PHP Chinese website!