c++ - 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 都转换为小数,进行加法然后再次转换?
谢谢你。
解决方案
由于您的类是多态的,因此该Add()
函数应该采用引用或指针参数:
class Array {
// ...
virtual Array& Add(Array&);
};
您现在可以Add()
使用不同的返回类型覆盖派生类:
class Hex: public Array {
// ...
Hex& Add(Array&) override;
};
返回类型必须是执行覆盖的类的引用类型。这是覆盖可以更改返回类型的唯一情况。
推荐阅读
- python - 将 tkinter 脚本转换为 .exe 文件后,尝试执行时出现错误:ModuleNotFoundError: No module named 'numpy'
- python - Pandas 系列仅将 NaN 填充到一定限制
- reactjs - Material UI:如何使用按钮的 onClick 事件获取滑块值?
- java - 如何在 Eclipse 项目中设置默认下载目录以下载 .pdf 文件?
- c - C结构语法问题
- arrays - 带有包含空格的条目的 Bash 数组扩展
- sql - 复制逻辑:计数不同
- python - I get 'decimal.Decimal' object is not callable when testing code
- css - Dynamic CSS counter crashes when using t, am I using '@property' or 'counter' wrong?
- jenkins - Re-run a kuberenetes job without deleting the previous job