Home >Backend Development >C++ >How to Define a Virtual `

How to Define a Virtual `

DDD
DDDOriginal
2024-10-26 19:12:03908browse

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>

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>

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!

Statement:
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