我做了分数和模板函数Sum类,应该将分数数组求和。但是当我尝试执行此功能时它说这是错误的类型 (不允许输入类型名称)。
class Fraction{
public:
int numerator;
unsigned denominator;
Fraction() {};
Fraction(int nume, unsigned denom = 1);
Fraction operator += (const Fraction &u);
};
Fraction::Fraction(int nume, unsigned denom)
{
numerator = nume;
denominator = denom;
}
Fraction Fraction::operator += (const Fraction &u)
{
int a, b, product, LCM; //least common multiple
a = denominator;
b = u.denominator;
product = a*b;
do
{
if (a > b) a = a - b;
else b = b - a;
} while (a != b);
LCM = product / a;
numerator = (LCM / denominator)*numerator + (LCM / u.denominator)*u.numerator;
denominator = LCM;
return *this;
}
template <class T>
T Summ(int count, T *array)
{
T sum = 0;
for (int i = 0; i < count; i++)
sum += array[i];
return sum;
}
主要
cout << Summ(2, Fraction) << endl;
我不想更改Summ函数。 我想要分数数组
Fraction *tab = new Fraction[2];
tab[0] = Fraction(2, 4);
tab[1] = Fraction(5, 6);
,然后求和。 类似于
int ints[8] = {1,2,3,4,-5,6,-12,16};
cout << Summ(8, ints) << endl;