以下是我的文件TotalTemplate.cpp:
#include <iostream>
#include "conio.h"
using namespace std;
template<class T>
class TotalTemplate{
public:
//protected:
T* items;
int itemsAdded;
int amountOfItems;
//public:
//Exception for trying to add items when its passed its limit
class TooManyItems{ };
//Exception for trying to call total before the total has been reached
class IncompleteTotal{ };
TotalTemplate(int amountOfItems){
TotalTemplate::amountOfItems = amountOfItems;
items = new T[amountOfItems];
itemsAdded = 0;
}
TotalTemplate(int amountOfItems, T firstItem){
TotalTemplate::amountOfItems = amountOfItems;
items[] = new T[amountOfItems];
items[0] = firstItem;
itemsAdded = 1;
}
void addItem(T item){
if (itemsAdded >= amountOfItems)
throw TooManyItems();
else{
items[itemsAdded-1] = item;
itemsAdded++;
}
}
//Returns the amount of items added so far
int getAmountAdded(){
return itemsAdded;
}
T getTotal(){//Here is the method definition that is giving me problems
if (itemsAdded < amountOfItems)
throw IncompleteTotal();
else{
T total=items[0];
for (int i = 1; i < itemsAdded; i++)
total += items[i];
return total;
}
}
};
void main(){
//using int to fill the generic type T
cout << "Enter the amount of items to be totaled: ";
int totalAmountOfItems = getInt();
TotalTemplate<int> *total=new TotalTemplate<int>(totalAmountOfItems);
while (true){
cout << total->getAmountAdded() << " items added so far!\nSelect one of the following actions to take.\n";
cout << "(1) Add an item.\n";
cout << "(2) View total.\n";
cout << "(3) Exit Program.\n";
switch (menuSelect(3)){
case 1://Add an item
try{
cout << "Enter a number to add: ";
int item = getInt();
total->addItem(item);
}
catch (TotalTemplate<int>::TooManyItems){
cout << "\nItems given exceeds expected limit.\n\n";
}
break;
case 2://View Total
try{
int totalInt = total->getTotal(); //Here is my problem
cout << "The total is: " << totalInt << endl<<endl;
}
catch (TotalTemplate<int>::IncompleteTotal){
cout << "\nRunning Total has not yet reached total amount of items yet.\n\n";
}
break;
case 3: //Exit program
return;
}
}
cout << "\n\nExiting program...";
_getch();
}
我遇到的问题是在 main 方法中,当我调用 total.getTotal() 时,我没有返回预期的 int,而是所有项目加在一起的总和,我得到了一个完全随机的 int 输出:- 842150451
我的猜测是它正在输出一些东西而不是从 getTotal() 返回的值,但我不确定如何或为什么或如何修复它。我来自 Java 背景,所以我觉得我不习惯做不正确的 oop C++ 练习。
此外,getInt() 和 menuSelect() 是我在之前的代码中多次重复使用的方法,因此为了简单起见,我将它们从文件中排除。
有人知道我做错了什么吗?
最佳答案
addItem
中的这一行
items[itemsAdded-1] = item;
应该是
items[itemsAdded] = item;
关于C++:当使用从对象的getter方法调用的值时,输出一个随机的负整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33399047/