最近我有一個面向對象的測試,問題並不那麼艱難,但他們給我的信息讓我問自己如何使用它。下面是代碼和有,我創建測試和看到一些代碼(我給的,我創建的代碼註釋)如何在類中的屬性/變量中使用組合類作爲矢量類型
#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);
所以我真正想知道的部分是:
- 如何利用這些代碼,這樣類似 上面的代碼的東西都可以使用(或更好的只是使用反推功能 創建新實例,因爲它的載體)
////
vector<Saving> accounts;
void addAccount(Saving account);
- 爲什麼如果創建的我不能編譯 「保存accounts2;」
我知道有關的push_back功能,但它只是沒有想到要使用@Vicente怎麼寫的,因爲我剛開始編程,所以我只知道如何使用普通類型添加元素而不使用類。 所以我測試一些代碼,但我似乎無法弄清楚如何打印帳戶 下面是我測試過 '無效addAccount(儲蓄賬戶)' '{ 賬戶。的push_back(帳戶); }' '空隙打印()' '{ COUT << 「ACCNO:」 <<帳戶[0] .accno << 「平衡:」 <<帳戶[0] << .balance ENDL; }' – hafhaf100