6.1.3 Định nghĩa một phân lớp đơn giản (3)
Các đối tượng của lớp Sub có thể làm hầu hết những thứ giống như các anh chị của chúng được tạo ra từ lớp Super. Chúng […]
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#include <iostream> using namespace std class Element { int value; public: Element(int val) { value = val; cout << "Element(" << val << ") constructed!" << endl; } int Get(void) { return value; } void Put(int val) { value = val; } } class Collection { Element el1, el2; public: Collection(void) { cout << "Collection constructed!" << endl; } int Get(int elno) { return elno == 1 ? el1.Get() : el2.Get(); } int Put(int elno, int val) { if(elno == 1) el1.Put(val); else el2.Put(val); } }; int main(void) { Collection coll; return 0; } |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#include <iostream> using namespace std; class Element { int value; public: Element(void) { cout << "Element constructed!" << endl; } int Get(void) { return value; } void Put(int val) { value = val; } }; class Collection { Element el1, el2; public: Collection(void) { cout << "Collection constructed!" << endl; } int Get(int elno) { return elno == 1 ? el1.Get() : el2.Get(); } int Put(int elno, int val) { if(elno == 1) el1.Put(val); else el2.Put(val); } }; int main(void) { Collection coll; return 0; } |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
#include <iostream> using namespace std; class Array { int *values; int size; public: Array(int siz) { size = siz; values = new int[size]; cout << "Array of " << size << " ints constructed." << endl; } ~Array(void) { delete [] values; cout << "Array of " << size << " ints destructed." << endl; } int Get(int ix) { return values[ix]; } void Put(int ix, int val) { values[ix] = val; } }; int main(void) { Array *arr = new Array(2); for(int i = 0; i < 2; i++) { arr->Put(i, i + 100); } for(int i = 0; i < 2; i++) { cout << "#" << i + 1 << ":" << arr->Get(i) << endl; } delete arr; return 0; } |
Copyright © 2026 CppDeveloper by Phạm Minh Tuấn (SHUN)