findacct
가 특정 계정에 아무것도하지 않기 때문에 클래스 내부에서 이동하는 기능의 나쁜 예이며, 단지 몇 ACCO 중 검색 unts.
static
멤버 함수로 BankAccount
클래스 내부에서 이러한 종류의 함수를 이동할 수 있지만 정적 멤버 함수는 멋진 이름을 가진 전역 함수와 크게 다르지 않습니다.
OOP 접근 방식에 대해 훨씬 더 흥미로운 것은 BankAccount
클래스 내부의 특정 은행 계좌에서 작동하는 일부 기능을 이동하는 것입니다. 다음 예제 코드에서
bool BankAccount::withdraw(int amount)
에
bool withdraw(int account_id, int amount)
에서 변화 같은 것을 나는 개인 벡터의 모든 계정을 저장했습니다. 새 계정을 만들려면 ID 번호를 제공하는 정적 클래스 함수를 호출해야합니다. 이 코드에는 많은 미묘한 부분이 포함되어 있으며 완전히 이해하지 못하는 한 기본으로 사용하는 것은 위험 할 수 있습니다 ... 이는 논리적으로 논리적 인 구문이 논리적으로 작용하거나 컴퓨터가 이상하게 작동 할 수있는 C++의 특징입니다. 내 제안은 좋은 C++ 책을 들고 언어를 실험하기 전이나 시험 할 때 커버하는 책을 읽는 것입니다.
C++은 너무 복잡하고 때로는 비논리적인데 (역사적인 이유로) 실험을 통해서만 배울 수 있습니다.
#include <vector>
#include <algorithm>
#include <stdlib.h>
#include <stdio.h>
class BankAccount
{
private:
int id; // Unique identifier for this account
int balance; // How much money is present on this account
static std::vector<BankAccount*> accounts; // Global list of valid accounts
// Constructor - private!
BankAccount(int id) : id(id), balance(0)
{
// Add to global accounts list
accounts.push_back(this);
}
// Destructor - also private
~BankAccount()
{
// Remove from global accounts list
accounts.erase(std::find(accounts.begin(), accounts.end(),
this));
}
public:
// Public global function to create a new account
static bool createAccount(int id)
{
if (find(id) != NULL)
{
return false;
}
else
{
new BankAccount(id);
return true;
}
}
// This is a global function that given the unique identifiers
// returns a pointer to the account or NULL if non-existent
static BankAccount *find(int id)
{
for (int i=0,n=accounts.size(); i<n; i++)
if (accounts[i]->getId() == id)
return accounts[i];
return NULL;
}
// This is a global function that transfers money from one
// account to another and returns true if the operation is
// successful (i.e. if the source account has enough money)
static bool transfer(int from_id, int to_id, int amount)
{
BankAccount *from = find(from_id);
BankAccount *to = find(to_id);
if (from != NULL && // Is first account valid?
to != NULL && // Is second account valid?
from->withdraw(amount)) // Is there enough money?
{
to->deposit(amount); // move the withdrawn money
return true;
}
else
{
// Operation did not succeed
return false;
}
}
// Returns the id of the account
int getId()
{
return id;
}
// Returns the current balance for the account
int getBalance()
{
return balance;
}
// Deposit a sum on the bank account
void deposit(int amount)
{
balance += amount;
}
// Tries to withdraw the specified amount from the account
bool withdraw(int amount)
{
if (amount <= balance)
{
balance -= amount;
return true;
}
else
{
return false;
}
}
};
// This is also needed; the declaration of accounts inside
// the class (.h) doesn't actually allocate the vector... simply
// tells that the following line will be present in a .cpp
std::vector<BankAccount*> BankAccount::accounts;
///////////////////////////////////////////////////////////////////////////////////
// Do some test...
#define check(x) \
do { printf("check: %s\n", #x); if (!(x)) { \
printf("*** Fatal error (line %i)", __LINE__); \
exit(1); }}while(0)
int main(int argc, const char *argv[])
{
check(BankAccount::createAccount(6502) == true);
check(BankAccount::createAccount(386) == true);
// duplicate account!
check(BankAccount::createAccount(6502) == false);
// Not enough founds
check(BankAccount::transfer(386, 6502, 1000) == false);
// Deposit
BankAccount *p386 = BankAccount::find(386);
check(p386 != NULL);
p386->deposit(1000);
// Valid and invalid transfers...
check(BankAccount::transfer(386, 6502, 1000) == true); // ok
check(BankAccount::transfer(386, 6502, 1000) == false); // No more funds
check(BankAccount::transfer(6502, 386, 500) == true); // Give some back
check(BankAccount::transfer(386, 6502, 1000) == false); // Not enough funds
check(BankAccount::transfer(386, 6502, 400) == true); // ok
check(BankAccount::find(386)->getBalance() == 100);
check(BankAccount::find(6502)->getBalance() == 900);
return 0;
}
'{int main()}'을 (를) 컴파일하기위한 명성이 – fizzer