编译错误是: '初始化':无法从'int'转换为'Money' 文件:genericarray.h 行:13
这是我的主要功能
int main()
{
genericArray<Money>m3(5);
Money d(-1, 89);
Money a(10, 5);
Money b(10, 5);
Money c(43, 7);
Money k(50, 6);
Money m(10, 20);
Money bonus(5, 0);
m3.elements[0] = a;
m3.elements[1] = b;
m3.elements[2] = c;
m3.elements[3] = k;
m3.elements[4] = m;
m3.total = m3.sum();
m2.total = m2.sum();
m1.total = m1.sum();
return 0;
}
这是我的Assignment运算符重载Money类和Money类本身
class Money
{
private:
int lira;
int kurus;
public:
Money() { lira = 0; kurus = 0; }
Money(int a, int b);
~Money() {}
void operator=(const Money& money2) { this->lira = money2.lira; this->kurus = money2.kurus; }
void operator=(int l) { this->lira = l; this->kurus = 0; }
这是我的带有sum()函数的genericArray类
template <class Type>
class genericArray
{
private:
int size;
public:
Type* elements;
Type total;
Type sum()
{
Type sumAll = 0;
for (int i = 0; i < size; i++)
{
sumAll += elements[i];
}
if (sumAll > 100)
sumAll += 5;
return sumAll;
}
genericArray() { elements = NULL; size = 0; }
genericArray(int arrSize) { elements = new Type[arrSize]; size = arrSize; }
~genericArray() { delete[] elements; }
};
答案 0 :(得分:1)
使用单个int参数编写新构造函数解决了问题:
Money(const int a)
{
if (a < 0) throw "The amount of money can not be below zero!";
this->lira = a;
this->kurus = 0;
}
重点是
Type sumAll = 0;
只调用只占用1个int而不是调用默认构造函数和赋值运算符的构造函数。