C++ 在类文件中使用用户定义的类向量

C++ 在类文件中使用用户定义的类向量,c++,class,vector,member-functions,C++,Class,Vector,Member Functions,我有一个名为Account的类,具有以下参数: Account::Account(string ibanCode, string paramOwner, double amount) {} 我在主函数中创建了一个由类帐户组成的向量: accs.push_back(Account(fullName, iban, value)); 我想编写一个函数,通过名为displayAll()的类成员函数打印向量中的所有帐户值,目前为止我尝试了以下方法: void Account::displayAll()

我有一个名为Account的类,具有以下参数:

Account::Account(string ibanCode, string paramOwner, double amount) {}
我在主函数中创建了一个由类帐户组成的向量:

accs.push_back(Account(fullName, iban, value));
我想编写一个函数,通过名为displayAll()的类成员函数打印向量中的所有帐户值,目前为止我尝试了以下方法:

void Account::displayAll() 
{

  for (int i = 0; i < accs.size(); i++)
  {
    cout << accs[i].displayBalance() << endl;;
  }
}
void帐户::displayAll()
{
对于(int i=0;icout我认为让它成为一个成员会非常复杂,最好的选择应该是使用一个可以访问参数的普通函数

    #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);
    }
#包括
#包括
使用名称空间std;
结构帐户{
帐户(字符串ibanCode,字符串paramOwner,双倍金额):\u amount(amount),\u ibanCode(ibanCode),\u paramOwner(paramOwner){};
字符串_ibanCode;
字符串_参数所有者;
双倍金额;
};
void DisplayAll(常量向量和Accs){
用于(const auto&Acc:Accs){

如果想让
Account
了解所有帐户,请尝试将
accs
设置为
Account
静态成员,而不是主函数中的局部变量。管理这样的静态向量将是一团混乱。只需将
displayAll
设置为自由函数,而不是将向量作为输入参数的类成员即可nt:
void displayAll(const std::vector&accs){/*body保持不变*/}
想想你在问什么,你有一个类,你用这个类的对象填充一个向量,但是你想让容器内的一个对象打印容器的全部内容,这是一个糟糕的设计,没有优雅的解决方案来实现这一点。