c++ - 虚函数设计问题

标签 c++ inheritance

我有一个基类,目前我有一个名为 get_value() 的方法,它应该返回适​​当转换为各种原始数据类型的值。由于我们不能拥有仅返回类型不同的虚拟方法,因此我必须执行以下操作:

virtual void get_value(unsigned int index, unsigned char & r) const = 0;
virtual void get_value(unsigned int index, char & r) const = 0;
virtual void get_value(unsigned int index, unsigned short & r) const = 0;
virtual void get_value(unsigned int index, short & r) const = 0;
virtual void get_value(unsigned int index, unsigned int & r) const = 0;
virtual void get_value(unsigned int index, int & r) const = 0;
virtual void get_value(unsigned int index, float & r) const = 0;
virtual void get_value(unsigned int index, double & r) const = 0;

从维护的角度来看,这很烦人,而且使用起来有点尴尬,因为用户必须执行以下操作:

unsigned char v;
obj->get_value(100, v);

无论如何,所有子类都必须为这些类型中的每一个覆盖这一事实很烦人。我想知道是否有人有任何建议来避免这种情况,或者能够以某种方式通过仅使用一个虚拟函数以某种方式以更紧凑的方式执行此操作。

子类可以是这样的:

void get_value(unsigned int index, unsigned char & r) const {get<unsigned char>(index, r);}
void get_value(unsigned int index, char & r) const {get<char>(index, r);}
void get_value(unsigned int index, unsigned short & r) const {get<unsigned short>(index, r);}
void get_value(unsigned int index, short & r) const {get<short>(index, r);}
void get_value(unsigned int index, unsigned int & r) const {get<unsigned int>(index,r);}
void get_value(unsigned int index, int & r) const {get<int>(index,r);}
void get_value(unsigned int index, float & r) const {get<float>(index,r);}
void get_value(unsigned int index, double & r) const {get<double>(index,r);}

这个专门的模板 get 方法为每个子类做一些特定的事情。

最佳答案

您应该考虑只创建不同的函数。

int getInt();
double getDouble();

等等。

看来您的调用代码必须知道任何情况下的区别。由于对您可以执行的操作没有真正的抽象(显然,至少),您最好弄清楚区别。模板和面向对象的类可能只会增加不必要的复杂性。

当然,为了判断这一点,可能需要更多的上下文。只是我的 0.02 欧元 :)

关于c++ - 虚函数设计问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22231749/

相关文章:

java - 组织.hibernate.InstantiationException : Cannot instantiate abstract class or interface

C# 子类返回类型的协方差

c++ - 无符号字符到 SetWindowTextA

c++ - sigaction 结构和函数

c++ - 存储无效指针是否会自动执行未定义行为?

javascript - 我想克隆一个 javascript 类。向克隆属性添加方法而不实际覆盖现有方法?

java - 解释一下Java中的多态性?

c++ - 为什么 delete 仅在 main 中起作用,而在将要删除的一个或多个对象作为输入的函数中不起作用?

c++ - 如何在 C++ 中使用构造函数初始化二维 vector ?

c++ - 如何从基类指针访问顶层类中的变量