首页 > 解决方案 > 2 个派生类的虚函数(十六进制 + 二进制)

问题描述

我有基类 Array,其中有虚函数 Add 以进行添加

class Array
{
public:
    unsigned char arr[100] = { 0 };
    int size;
    Array();
    Array(int);
    char operator[](int);
    virtual Array& Add( Array);
};

我有两个派生类 Hex(用于存储十六进制数)和 BitString(用于存储二进制数):

class BitString : public Array
{
public:
    BitString& operator&(BitString&);//and
    BitString& operator|(BitString&);//or
    BitString& operator^(BitString&);//xor
    BitString& operator~();//not
};

class Hex: public Array
{
public:
    Hex& operator+(Hex);
    Hex& operator-(Hex);
    Hex& operator*(Hex);
    Hex& operator/(Hex);
    bool operator==(const Hex);
    bool operator>(const Hex);
    bool operator<(const Hex);
    Hex DecToHex(int);
};

我的任务,除了 Hex 和 BitString 的 make 运算符之外,是覆盖虚拟 Add 函数以添加 BitString 和 Hex 对象。

我没有正确得到:

1) 我需要在 Hex 和 BitString 中创建 2 个函数

2)这些函数应该返回什么?十六进制、位串或数组。

3)最快的方法是什么?将 Hex 和 BitString 都转换为小数,进行加法然后再次转换?

谢谢你。

标签: c++

解决方案


由于您的类是多态的,因此该Add()函数应该采用引用或指针参数:

class Array {
    // ...

    virtual Array& Add(Array&);
};

您现在可以Add()使用不同的返回类型覆盖派生类:

class Hex: public Array {
    // ...

    Hex& Add(Array&) override;
};

返回类型必须是执行覆盖的类的引用类型。这是覆盖可以更改返回类型的唯一情况。


推荐阅读