2011-03-06 74 views
0

任何人都知道如何實現一個函數來使用類並將功能移入類中。我如何添加適當的成員函數(或方法),以便實現函數的功能..也許可能添加參數化的構造函數?例如,如何將我的函數這樣做最初是這樣的:類,成員函數和單獨編譯

//constant definitions 
const int MAX_NUM_ACCOUNTS = 50; 

BankAccount account[MAX_NUM_ACCOUNTS]; 

int findacct(const BankAccount account[], int num_accts, int requested_account); 

{int main()} 

// Function findacct: 
int findacct(const BankAccount account[], int num_accts, int requested_account) 
{ 
    for (int index = 0; index < num_accts; index++) 
     if (account[index].acct_num == requested_account) 
      return index; 
    return -1; 
} 
+0

獲得'{int main()}'編譯的榮譽 – fizzer 2011-03-06 10:21:59

回答

0

我不知道你所使用的編程語言,因此我已經寫的很簡短sudo的代碼,希望能對大家幫助

Class BankAccount{ 
    //first you need to list its properties e.g. 
    int accountNumber; 
    string name; 

    //and then you can either construct a constructor or just use the default constructor 

    //then you declare your method within the related class 
    int findacc(BankAccount account[], int num_acc, int req_acc){ 
     for(int i=0; i < num_acc; i++){ 
      if... 
       return... 
     } 
     return 1; 
    } 
} 

您的main()

BankAccount bank = new BankAccount(); //calling the constructor 
bank.findacc(pass the parameter) 
+0

Im us ing C++語言 – NewbieLB 2011-03-06 08:17:28

0

findacct是函數的壞榜樣,一個類裏面移動,因爲沒有在一個特定的帳戶做任何事情,在幾個ACCO只是搜索UNTS。

您可以將BankAccount類中的這種類型的函數作爲static成員函數移動,但靜態成員函數與帶有奇特名稱的全局函數沒有多大區別。

對於面向對象方法更有意思的是,將移動一些作用於BankAccount類中的特定銀行帳戶的函數,例如,像從

bool withdraw(int account_id, int amount) 

更改爲

bool BankAccount::withdraw(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; 
} 
+0

好吧,我明白你的意思了。對於像撤退這樣的函數,我確實有這樣的功能,但它構成了令我困惑的構造函數。至於要在參數中添加什麼以及它們本身。例如我的提款功能:void withdraw(BankAccount account [],int num_accts,ofstream&out4) – NewbieLB 2011-03-06 08:23:14

+0

我已經添加了一個完整的示例。請注意,除非你完全理解它的每一點,否則你不應該使用它;進行看起來語法上合乎邏輯的更改,甚至在沒有任何警告的情況下編譯仍然可能實際上做非常糟糕的事情。這不幸是C++的一個特點......你應該先通過閱讀一本好書來學習它。學習C++通過編譯器的實驗或多或少是一種自殺(C++太複雜且不合邏輯)。 – 6502 2011-03-06 09:46:14

0

我不知道你問究竟是什麼,但這裏有一些意見:

  1. 不要使用固定大小的數組。你要麼浪費空間要麼溢出。使用矢量。

  2. 不要使用像num_accts或acct_num這樣的縮寫,使用可讀的名稱。我會用number_of_accounts代替前者,後者代替number,因爲它是結構的一部分。

  3. 不要自己寫線性搜索算法,它們已經在STL中實現了。你所要做的就是提供一個比較帳號的謂詞。

這裏是基於這些觀察一些示例代碼:

#include <algorithm> 
#include <vector> 

std::vector<BankAccount> accounts; 

class AccountNumberComparer 
{ 
    int account_number; 

public: 

    AccountNumberComparer(int account_number) 
    : account_number(account_number) {} 

    bool operator()(const BankAccount& account) const 
    { 
     return account.number() == account_number; 
    } 
}; 

int main() 
{ 
    // ... 

    std::vector<BankAccount>::iterator it = 
    std::find_if(accounts.begin(), accounts.end(), AccountNumberComparer(123)); 

    if (it != accounts.end()) 
    { 
     // use *it 
    } 
    else 
    { 
     // no such account 
    } 
} 

如果你無法理解這個代碼,我建議你得到一個good C++ book


等等AccountNumberComparer書面的東西需要的是什麼用C幾乎無用++我看來,使<algorithm>

嘛,你不編寫特定的代碼爲每find_if電話,你可以去通用,而不是:

template <class Class, typename Result, Result (Class::*MemFun)() const> 
class Comparer 
{ 
    const Result& value; 

public: 

    Comparer(const Result& value) : value(value) {} 

    bool operator()(const Class& x) const 
    { 
     return (x.*MemFun)() == value; 
    } 
}; 

// ... 

std::vector<BankAccount>::iterator it = 
std::find_if(accounts.begin(), accounts.end(), 
      Comparer<BankAccount, int, &BankAccount::number>(123)); 

和當然,Boost已經提供了更好的解決方案:

std::vector<BankAccount>::iterator it = 
std::find_if(accounts.begin(), accounts.end(), 
      boost::bind(&BankAccount::number, _1) == 123); 
+1

編寫'AccountNumberCompare'這類東西的需求,使得在我看來''在C++中幾乎沒有用處。聲明式方法只有當你得到的內容比簡單的代碼更加簡潔和可讀時纔是很好的。不幸的是,C++語法太麻煩了(可能是C++ 0X lambda將至少部分解決這個問題)。 – 6502 2011-03-06 09:54:29

+0

@ 6502查看我的更新。 – fredoverflow 2011-03-06 10:59:40