c ++运算符重载多态性 [英] c++ operator overloading & polymorphism

查看:93
本文介绍了c ++运算符重载多态性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

多态性和运算符重载混合在一起吗? 您不能在没有指针的情况下进行多态,如此答案中所述,您也可以如此处所述,不会使用指针进行运算符重载.
所以真的没有办法做到这一点,对吧?

Do polymorphism and operator overloading mix together? You can't do polymorphism without pointers, as it is explained in this answer and also you can't do operator overloading with pointers as explained here.
So there really is no way to do this, right?

推荐答案

是的.您没有正确阅读答案.

Yes there is. You didn't read the answers properly.

这是一个简短的演示:

#include <iostream>
using namespace std;

struct X
{
    int value;
    virtual void operator += (int x)
    {
        value += x;
    }
};

struct Y : X
{
    virtual void operator += (int x)
    {
        value *= x;
    }
};

void do_stuff(X& x)
{
    x += 10;
    cout << "Final value " << x.value << endl;
}

int main()
{
    X x;
    x.value = 10;
    Y y;
    y.value = 10;
    do_stuff(x);
    do_stuff(y);

    return 0;
}

我并不是在暗示这是一个好主意,也不是实用的.只是有可能.

I'm not implying that this is a good idea, or that it's practical. It's simply just possible.

这篇关于c ++运算符重载多态性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆