所以我试图创建一个bankaccount程序,它实际上将使用从一个名为statistics(statistics.cpp / statistics.h)的单独.cpp / .h程序派生的两个单独的类。我已经包含了标题在适当的位置内的文件,并确保我没有做出任何区分大小写的错误。向前进。我遇到的问题是我收到了错误 - "警告:未使用的变量'提款'未设定。" - "警告:未使用的变量'存款'未设置。"
我在statistics.cpp中正确地创建了构造函数/重载构造函数
Statistics::Statistics(){
size = 0;
pData = nullptr;
capacity = 0;
}
Statistics::Statistics(int capacity){
pData = new double [capacity];
size = 0;
//int i = 0;
}
以及在我的statistics.h文件中定义它
class Statistics{
public:
Statistics();//default constructor
Statistics(int capacity);//...
在我的bankaccount.h文件中,我添加/创建了两个单独的类,以尝试开发聚合关系。
//....
private:
double amount = 0;
int transactions = 0;
double value = 0;
Statistics* deposits;
Statistics* withdrawals;
};
#endif
这就是我在bankaccount.cpp中初始化和设置类的方法
int main(){
//Statistics aStatistics; Constructor of Statistics
//aStatistics.test(); Test function for Statistics .cpp/.h files (Was
//successful)
bankaccount abankaccount;
abankaccount.test();
return 0;
}
void bankaccount::test(){
cout << "Hello, Welcome to Boca Regional Bank." << endl;
cout << "**********************************************" << endl;
cout << "What is the expected amount of transactions for this month?"
<<endl;
cin>> transactions;
Statistics withdrawals = Statistics(transactions); //"Warning: unused variable 'withdrawals'"
Statistics deposits = Statistics(transactions); //"Warning: unused variable 'deposits'"
int userchoice;
do{
cout << "\n";
userchoice = getuseroption();
process(userchoice,transactions);
} while (userchoice != 0);
}
void bankaccount::process(int option, int transactions){
switch (option){
case 1:
double temp1;
cout <<endl;
cout << "You've chosen to deposit into your Bank Account."
<< endl;
cout << "Your current balance is " << amount << endl;
cout << "How much would you like to deposit?" << endl;
cin >> temp1;
while ((temp1 < 0) || (temp1 > 100000) ){
cout << "You've entered an invalid amount, please try
again."<<endl;
cout << "How many would you like to deposit?"<<endl;
cin >> temp1;
}
deposit(&amount,temp1);
if (temp1 > 0){
deposits->add(temp1); //Implementation of one of the functions
//from the statistics class
//At this point the program crashes
}
else if (temp1 == 0){
break;
}
break;
....}
这是Statistics .cpp / .h add();功能
void Statistics::add (double value){
pData[size]=value;
size++;
}
答案 0 :(得分:0)
您好像要初始化deposits
中withdrawals
个实例的bankaccount
和bankaccount::test()
成员。但是,Statistics withdrawals = Statistics(transactions);
只是创建一个局部变量并对其进行初始化。由于它从未使用过,编译器警告您可能打算做其他事情(比如初始化成员)。
你可能意味着:
withdrawals = new Statistics(transactions);
deposits = new Statistics(transactions);
如果这样做,则必须在delete
析构函数中bankaccount
这些对象,以避免内存泄漏。现代C ++提供了更好的方法来做到这一点,但这是非常不合适的。
注意:用户代码中的类名通常位于CamelCase
,而不是alllowercase
。