问题描述
我有一个名为Account的类,具有以下参数:
Account::Account(string ibanCode,string paramOwner,double amount) {}
我在主函数中创建了一个由Accounts类组成的向量:
accs.push_back(Account(fullName,iban,value));
我想编写一个函数,通过名为displayAll()的类成员函数来打印矢量中的所有Account值,到目前为止,我已经尝试过:
void Account::displayAll()
{
for (int i = 0; i < accs.size(); i++)
{
cout << accs[i].displayBalance() << endl;;
}
}
我想将其写入类文件中。你有什么建议吗?
解决方法
我认为使其成为成员会非常复杂,最好的选择应该是使用可以访问参数的普通函数。
#include <iostream>
#include <vector>
using namespace std;
struct Account {
Account (string ibanCode,string paramOwner,double amount) : _amount(amount),_ibanCode(ibanCode),_paramOwner(paramOwner) {};
string _ibanCode;
string _paramOwner;
double _amount;
};
void DisplayAll (const vector<Account>& Accs) {
for (const auto& Acc : Accs) {
cout << Acc._ibanCode<<' '<<Acc._paramOwner<<' '<< Acc._amount<<'\n';
}
return;
}
int main () {
vector<Account> Accs;
Accs.push_back(Account("SomeCode","SomeOwner",2.0));
Accs.push_back(Account("SomeOtherCode","SomeOtherOwner",3000.42));
DisplayAll(Accs);
}
为了避免使答案过于复杂,我制作了一个结构,但您可以使DisplayAll
函数成为该类的friend
或使一些吸气剂。