Home > Backend Development > C++ > body text

Why Can\'t I Make the `operator

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

Why Can't I Make the `operator

Implementing virtual operator<<

The need for a virtual operator<< arises when customizing the behavior of the streaming operator for different classes. Attempts to define the operator as virtual often lead to the error "operator <<: only member functions and bases can be virtual."

The Dilemma of Free Functions

The issue arises because operator<< is typically defined as a free function, which lacks a receiver object and cannot be virtual. Defining the operator as a member function, on the other hand, reverses the parameter order, causing a compilation error.

A Solution via Indirection

To resolve this dilemma, consider adding a virtual member function that encapsulates the desired output behavior:

<code class="cpp">class MyClass {
public:
    virtual void print(ostream& out) const; // Virtual output function
};</code>
Copy after login

Customized Operator with Virtual Behavior

With the virtual member function in place, you can define the operator<< as a free function that delegates to the print function:

<code class="cpp">ostream& operator<<(ostream& out, const MyClass& mc) {
    mc.print(out); // Calls the virtual print function
    return out;
}</code>
Copy after login

This approach maintains the correct parameter order for the operator<< free function while allowing customization of the output behavior through the virtual member function. Subclasses can override the print function to implement their own custom output formatting.

The above is the detailed content of Why Can\'t I Make the `operator. 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!