Home > Backend Development > C++ > body text

How to Define a Virtual `

DDD
Release: 2024-10-26 19:12:03
Original
824 people have browsed it

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&amp; where) const;
};</code>
Copy after login

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&amp; operator<< (ostream&amp; out, const MyClass&amp; mc) {
    mc.print(out);
    return out;
}</code>
Copy after login

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!

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
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!