最近我有一个面向对象的测试,问题不是那么难,但是他们给我的信息让我问自己如何使用它。下面是代码,我创建了一些代码来测试和查看(我对我创建的代码发表评论)
#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;
}
我创建的main函数中的所有代码都是为了查看输出的样子。
我认为以下代码是我们如何利用所有类的一部分 (但我仍然不知道如何使用矢量)
Saving s1(5000,600.00);
Saving s2(5001,111.11);
Bank b1;
b1.addAccount(s1);
b1.addAccount(s2);
所以我真正想知道的是:
////
vector<Saving> accounts;
void addAccount(Saving account);
答案 0 :(得分:0)
有关如何使用该向量的一些指导,请查看:http://www.cplusplus.com/reference/vector/vector/介绍此类。只是一个快速提示:在最常见的情况下,您通常会添加push_back
的向量。这将在向量的末尾添加一个元素。然后迭代它(Iteration over std::vector: unsigned vs signed index variable)并打印出所需的信息。
关于:Saving accounts2;
使您的程序无法编译是由于您没有默认构造函数。请参阅http://en.cppreference.com/w/cpp/language/default_constructor了解如何创建一个。
答案 1 :(得分:0)
在void addAccount(Saving account)
课程中实施Bank
功能,以便将帐户实际添加到帐户向量中:
void addAccount(Saving account) {
accounts.push_back(account);
}
在double getBalance()
课程中实施int getAccno()
和Account
功能,分别返回帐号和余额:
double getBalance() { return balance; }
int getAccno() { return accno; }
实施print()
课程的Bank
功能,以打印accounts
向量中存储的每个帐户的帐号和余额:
void print() {
for (vector<Saving>::iterator it = accounts.begin(); it != accounts.end(); it++) {
cout << "accno: " << it->getAccno() << " balance: " << it->getBalance() << endl;
}
}