Home > Backend Development > C++ > body text

How to Implement Virtual Operator Overloading in C ?

Mary-Kate Olsen
Release: 2024-10-26 22:01:29
Original
242 people have browsed it

 How to Implement Virtual Operator Overloading in C  ?

Virtual Operator Overloading

Background

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.

The Issue

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.

The Solution: Indirection

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!