【发布时间】:2020-10-28 15:17:10
【问题描述】:
我正在寻找一种更好的方法来定义全局变量。这只是一个用于练习使用功能的小型银行应用程序。这是根据 C++ 标准定义变量的正确方法吗?我不是 100% 确定这一点。我在main() 之外定义了它,但如果我没记错的话,这是不可以的。我尝试创建类,我尝试为函数创建参数,这是我弄清楚如何将变量传递给所有函数的唯一方法。
// banking.cpp : This file contains the 'main' function. Program execution begins and ends there.
#include <iostream>
using namespace std;
int total = 100;
void menu();
int deposit();
int withdraw();
int main()
{
menu();
return 0;
}
void menu()
{
int selection;
cout << "your total money right now is $" << total << endl;
cout << "select 1 for deposit." << endl;
cout << "select 2 for withdraw" << endl;
cin >> selection;
switch (selection)
{
case 1:
deposit();
break;
case 2:
withdraw();
break;
}
}
int deposit()
{
int depositAmount;
cout << "your current total is $" << total << endl;
cout << "how much would you like to deposit? " << endl;
cin >> depositAmount;
total = depositAmount + total;
cout << "your new total is $" << total << endl;
cout << "you will be returned to the main menu..." << endl;
menu();
return total;
}
int withdraw()
{
int withdrawAmount;
cout << "your current total is $" << total << endl;
cout << "how much would you like to withdraw? " << endl;
cin >> withdrawAmount;
total = total - withdrawAmount;
cout << "your new total is $" << total << endl;
cout << "you will be returned to the main menu..." << endl;
menu();
return total;
}
【问题讨论】:
-
不鼓励使用非常量全局变量,但您声明它的语法是正确的。
-
参见How to declare a global variable in C++,但在这种特定情况下,您可以使用局部变量并将其作为函数参数传递。
-
我正在寻找一种更好的方式来定义一个全局变量——“全局变量”和“更好”是两个不能一起出现的短语。
-
我想你已经声明了全局变量。并且以同样的方式声明全局变量的唯一正确方法 - 尽可能不要声明和使用它。
-
这看起来最好有一个以
total作为成员变量和deposit和withdraw作为成员函数的类。
标签: c++