“重载"是指具有不同参数集的纯虚函数 [英] "Overloading" pure virtual function with different set of arguments

查看:105
本文介绍了“重载"是指具有不同参数集的纯虚函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码示例

#include <iostream>
using namespace std;

class Color
{
public:
    virtual void mixColors(Color &anotherColor) = 0;
};

class RGB : public Color
{
public:
    void mixColors(RGB &anotherColor);
};

void RGB::mixColors(RGB &kol)
{
    return RGB(0xABCDEF);
}

我完全知道为什么此代码不起作用( RGB 中的 mixColors()没有实现纯虚函数,因为它具有不同的参数集).但是,我想问一下是否还有另一种方法可以解决这个问题.假设我要混合颜色,但对不同的颜色类别使用不同的算法.我将不胜感激.

I perfectly know why this code is not working (mixColors() in RGB is not implementing pure virtual function, because it has different set of arguments). However I would like to ask if is there another approach to solve this problem. Let's say I would like to mix colors, but using different algorithm for different color classes. I would appreciate any help.

推荐答案

为什么仍然需要在这里使用虚拟方法?

Why do you need a virtual method here anyway?

如果仅在参数是另一种RGB颜色的情况下混合RGB颜色才有意义,那么为什么要使用一般的mixColor(Color)方法.

If mixing an RGB color makes only sense if the argument is another RGB color, then why should there be a generatal mixColor(Color) method.

如果确实需要,可以覆盖并执行动态强制转换:

If you really need it, you could override and perform a dynamic cast:

class RGB : public Color
{
public:
    void mixColors(RGB &anotherColor);
    void mixColors(Color &c) override { return mixColors(dynamic_cast<RGB&>(c)); }
};

void RGB::mixColors(RGB &kol)
{
    return RGB(0xABCDEF);
}

这样,如果尝试将RGB与其他类的颜色混合,则会在运行时出现异常.

This way, you will get an exception at runtime if you try to mix an RGB with a color of a different class.

这篇关于“重载"是指具有不同参数集的纯虚函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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