任何人都知道如何实现一个函数来使用Classes并将功能移到类中。如何为每个类添加适当的成员函数(或方法)以实现函数的功能..也许可能添加参数化构造函数?例如,我最初会如何为这样的函数执行此操作:
//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 :(得分:0)
我不确定你使用的编程语言是什么,因此我写了简短的sudo-code,希望它能帮助
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)
答案 1 :(得分:0)
findacct
是一个在类中移动的函数的错误示例,因为它不会对特定帐户执行任何操作,只会在多个帐户中进行搜索。
您可以在BankAccount
类中将此类函数作为static
成员函数移动,但静态成员函数与具有奇特名称的全局函数实际上没有区别。
OOP方法更有趣的是移动某些功能,该功能作用于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;
}
答案 2 :(得分:0)
我不确定你究竟在问什么,但这里有一些观察:
不要使用常量大小的数组。你要么浪费空间,要么溢出它们。使用向量。
请勿使用num_accts或acct_num等缩写,请使用可读名称。我会用number_of_accounts
替换前者,用number
替换后者,因为它是结构的一部分。
不要自己编写线性搜索算法,它们已在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
这样的东西的需要使我认为<algorithm>
在C ++中几乎无用。
好吧,你没有有为每个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);