2011-03-06 2 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

답변

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; 
    } 
} 

도움을 주()

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

입니다. Im us ing C++ 언어 – NewbieLB

0

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; 
} 
+0

알았어. 무슨 뜻인지 알 겠어. 철수와 같은 기능을 위해 .. 나는 그런 기능을 가지고 있지만 그것은 나를 혼란스럽게하는 생성자를 구성하고있다. 매개 변수와 {} 자체에 무엇을 넣어야하는지에 관해서. 예를 들어 나의 철회 기능 : 무효 철수 (BankAccount 계정 [], int num_accts, ofstream 및 out4) – NewbieLB

+0

전체 예제를 추가했습니다. 당신이 그것을 전부 이해하지 못한다면 그것을 사용해서는 안된다. 구문 론적으로 논리적 인 것처럼 보이는 변경 사항을 만들 수 있으며 경고가 없어도 컴파일하면 여전히 실제로 매우 나쁜 작업을 수행 할 수 있습니다. 이것은 불행히도 C++의 특징입니다 ... 우선 좋은 책을 읽어야합니다. 컴파일러를 실험하여 C++를 배우는 것은 다소 자살입니다 (C++은 너무 복잡하고 비논리적입니다). – 6502

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 람다가 적어도 부분적으로이 문제를 해결할 수 있음). – 6502

+0

@ 6502 내 업데이트를 참조하십시오. – fredoverflow