如何在类的属性/变量中使用组合类作为向量类型

How to Use Composition Class as Vector Type in Attribute/Variable in a Class

本文关键字:组合 向量 类型 变量 属性      更新时间:2023-10-16

最近我做了一个面向对象的测试,问题不那么难,但他们给我的信息让我问自己如何使用它

#include <iostream>
#include <vector>
using namespace std;
class Account{
protected:
    int accno;
    double balance;
public:
    // I add the initialization part to make the program works
    // (In my test they don't provide because there is a question about that)
    Account(int accno, double balance) : accno(accno), balance(balance){};
    double getBalance();
    int getAccno();
    void deposit(double amount);
};
class Saving : public Account{
public:
    // Same reason as above for initialization
    Saving (int accno, double balance) : Account(accno,balance){};
    bool withdraw (double amount);
    void compute_interest();
    // I add this method/function to see how Saving object behave
    void print(){
        cout << "ID: " << accno << "     balance: " << balance << endl;
    }
};
class Bank{
    int ID;
    //Saving accounts2;// If I comment this line I can compile otherwise I can't even create a Bank object
    vector<Saving>accounts;// This is the line that I don't know how to make use of it
public:
    // The 2 methods/functions below & the attribute/variable "ID" I create to confirm my expectation
    void addID(int newID){
        ID = newID;
    }
    void printID(){
        cout << "ID: " << ID << endl;
    }
    void addAccount(Saving account);
    void print();
};
int main()
{
    Saving s1(1001,500.0);
    s1.print();
    Bank b1;
    b1.addID(1111);
    b1.printID();
    return 0;
}

我创建的主函数中的所有代码都是为了查看输出的样子。

我认为以下代码是我们如何利用所有类的一部分(但我仍然不知道如何使用矢量(

Saving s1(5000,600.00);
Saving s2(5001,111.11);
Bank b1;
b1.addAccount(s1);
b1.addAccount(s2);

所以我真正想知道的是:

  1. 如何使用这些代码行,使类似可以使用上面的代码(或者最好只使用推回功能创建新实例,因为它是向量(

////

vector<Saving> accounts;
void addAccount(Saving account); 
  1. 为什么如果我创建"Saving accounts2;">

有关如何使用矢量的指导原则,请查看:http://www.cplusplus.com/reference/vector/vector/介绍这门课。只是一个快速提示:在最常见的情况下,您通常使用push_back添加到向量中。这将在矢量的末尾添加一个元素。然后对它进行迭代(对std::vector:unsigned vs signed index变量进行迭代(,并简单地打印出所需的信息。

关于:Saving accounts2;使您的程序不可编译是因为您没有默认的构造函数。请参阅http://en.cppreference.com/w/cpp/language/default_constructor关于如何创建一个。

Bank类中实现void addAccount(Saving account)函数,将帐户实际添加到帐户向量中:

void addAccount(Saving account) {
    accounts.push_back(account);
}

Account类中实现double getBalance()int getAccno()函数,分别返回账号和余额:

double getBalance() { return balance; }
int getAccno() { return accno; }

实现Bank类的print()功能,打印存储在accounts矢量中的每个账户的账号和余额:

void print() {
   for (vector<Saving>::iterator it = accounts.begin(); it != accounts.end(); it++) {
      cout << "accno: " << it->getAccno() << " balance: " << it->getBalance() << endl;
  }
}