我想知道如果你有C++類中的成員具有相同的參數,如果有一種方法來簡化這個?例如:一個班級成員的相同論點:簡化?
#include <iostream>
using namespace std:
class bankAccount
{
public:
bankAccount()
{
privAcct = "MyAccount";
privPin = "MyPin";
{
void changeBalance(string acct, string pin)
{
if(acct == privAcct && pin == privPin)
{
cout << "YAY! You can do this!" << endl;
}
}
void otherMethod(string acct, string pin)
{
if(acct == privAcct && pin == privPin)
{
cout << "YAY! You can do this!" << endl;
}
}
private:
string privAcct, privPin;
};
正如你可以看到他們都採取同樣的參數,並都需要在相同的條件是真實的訪問方法的「肉」。
雖然我在想可能會創建一個方法,然後爲了訪問方法的不同部分而使用switch語句,但我希望能夠訪問「changeBalance」部分或「 otherMethod「類的一部分。我只是不確定是否有辦法讓這個「整潔」一點,或簡化它?
我的整個代碼是這樣的:
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
void accountInfo();
class account{
public:
//constructor
account()
{
balance = 0.00;
accountNum = "0303";
pin = "2222";
}
//default for wrong entry response
void wrongEntry()
{
cout << "Wrong account number or PIN. Please try again.\n" << endl;
}
//change pin number
void changePin(string actNum, string oldPin)
{
if(actNum == accountNum && oldPin == pin)
{
string newPin;
cout << "Please enter in a new pin: ";
cin >> newPin;
pin = newPin;
cout << "Thank you." << endl;
}
else
{
wrongEntry();
}
}
//change balance
void changeBalance(string actNum, string pinnum)
{
if(actNum == accountNum && pinnum == pin)
{
double newAdd;
cout << "Your current balance is " << balance << "\nPlease enter the additional amount you would like to deposit: ";
cin >> newAdd;
balance += newAdd;
cout << "Your new balance is " << balance << ".\nThank you.\n" << endl;
}
else
{
wrongEntry();
}
}
//print balance and account #
void printBalance(string actNum, string pinnum)
{
if(actNum == accountNum && pinnum == pin)
{
cout << "For account #"<< accountNum << endl;
cout << "Your current balance is $" << balance << ".\nThank you.\n";
}
else
{
wrongEntry();
}
}
private:
string accountNum, pin;
double balance;
};
int main()
{
int input;
string aN, pin;
account bo;
while(1)
{
cout << "Please enter account number: ";
cin >> aN;
cout << "Please enter corresponding PIN: ";
cin >> pin;
///options
cout << "Please choose from the following options:\n";
cout << " 1. View Balance\n 2. Deposit\n 3. Change pin\nChoice: ";
cin >> input;
cout << endl;
switch(input)
{
case 1:
bo.printBalance(aN, pin);
break;
case 2:
bo.changeBalance(aN, pin);
break;
case 3:
bo.changePin(aN, pin);
break;
default:
cout << "The information you entered does not seem to match our records.\nPlease try again.\n";
break;
}
char response;
cout << "\nAre you done with your transaction?: Y/N";
cin >> response;
cout << endl;
if(response == 'Y' || response == 'y')
{
return 0;
}
}
}
我知道我應該把我的班級在不同的頭文件,以聲明的構造正確一起,但我只是希望簡化代碼。
謝謝。
不是美麗的乾淨C++的方式,但宏可以在這裏幫助。 – urzeit