The Polymorphism of C++ Technology Realizes the Virtualization of Non-member Function Behavior

1. Principle

The use of C++ polymorphism technology to realize the virtualization of the behavior of non-member functions refers to writing a virtual function in the polymorphic class to do the actual work, and adding a function is only responsible for calling the virtual function of the polymorphic class, according to the actual object pointed to by the input parameter Different call different virtual function implementations.

This method of binding through a polymorphic method, the input parameter variable can control different types of objects at runtime can be called dynamic parameterization .

2. Sample

#include <ostream>
#include <iostream>

using namespace std;

struct NLComponent
{
    virtual ostream& print(ostream& s) const = 0;
    // ...
};

struct TextBlock : NLComponent
{
    virtual ostream& print(ostream& s) const override 
    {
        cout << "TextBlock:" << __func__ << endl;
        // do something
        return s;
    }

    // ...
};

struct Graphic : NLComponent
{
    virtual ostream& print(ostream& s) const override 
    {
        cout << "Graphic:" << __func__ << endl;
        // do something
        return s;
    }
    // ...
};

// 具有多态行为的函数
inline ostream& operator<<(ostream& s, const NLComponent& c)
{
    return c.print(s);
}

int main()
{
    cout << TextBlock() << Graphic() << endl;

    return 0;
}

Program output:

Guess you like

Origin blog.csdn.net/xunye_dream/article/details/115036510