gpt4 book ai didi

c++ - 相同的函数,类层次结构的不同返回类型

转载 作者:太空宇宙 更新时间:2023-11-04 15:28:52 25 4
gpt4 key购买 nike

我们有一个看起来像这样的类层次结构:

class base
{
};

class derived1 : protected base
{
private:
float m_price;
int m_quantity;
float m_value;
public:
// float calculateValue();
};

class derived2 : protected base
{
private:
double m_price;
long m_quantity;
double m_value;
public:
// double calculateValue();
};

现在我们需要编写一个函数,通过将价格和数量相乘来计算值(value)。目的是使将来添加新类尽可能简单。您可能知道,这并不简单,因为这些字段的数据类型对于不同的类是不同的。实际上,我们使用这些函数在概念上做同样的事情,但在编程术语中它们是不同的操作。

为了尽量减少所需的剪切和粘贴量,目前我能想到的解决方案是使用模板函数:

template <class A, B, C>
A calculate_value(B price, C quantity)
{
A result;
// Some code to do the multiplication, not sure if template specialisation is needed
return result;
};

class derived1 : protected base
{
private:
float m_price;
int m_quantity;
float m_value;
public:
float calculateValue()
{
calculate_value < float, float, int > (m_price, m_quantity);
}
};

它的工作没问题,但这意味着我必须在每个类中定义每个成员函数。例如,如果我想要一个名为 getValue 的函数,我将需要另外很多模板函数。

类成员的数据类型在定义类时就已知了,因此必须将它们再次放入函数定义中似乎是重复的。有没有办法在函数定义中避免所有这些模板业务?

谢谢。

安迪

PS 我看到了下面的问题,但是那个问题中的问题略有不同: Returning different data type depending on the data (C++)

最佳答案

虽然我不能说我喜欢让多个派生类具有返回不同类型的函数的想法,但有一种方法可以做到这一点。

template
class base<typename value_type>
{
public:
value_type calculateValue();
};
class derived1 : protected base<float>
{
private:
float m_price;
int m_quantity;
float m_value;
};
class derived2 : protected base<double>
{
private:
double m_price;
long m_quantity;
double m_value;
};

这使您可以在派生类中改变 value_type,但在基类中声明所有常用函数(就像您应该做的那样)。这类似于 STL 中用于 map 等的方法。

关于c++ - 相同的函数,类层次结构的不同返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/981563/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com