5.3.7 Hàm khởi tạo (constructor)
Một hàm có tên trùng với tên của class chứa nó được gọi là hàm khởi tạo (hoặc hàm tạo) – constructor. Hàm khởi tạo […]
|
1 2 3 4 5 6 7 |
class Sample { public: void setVal(int value); int getVal(void); private: int value; }; |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#include <iostream> using namespace std; int main(void) { AddingStack super_stack; for(int i = 1; i < 10; i++) { super_stack.push(i); } cout << super_stack.getSum() << endl; for(int i = 1; i < 10; i++) { super_stack.pop(); } cout << super_stack.getSum() << endl; return 0; } |
|
1 2 |
45 0 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class { private: int stackstore[100]; int SP; public: Stack(void) { SP = 0; } void push(int value); int pop(void) { return stackstore[--SP]; } }; void Stack::push(int value) { stackstore[SP++] = value; } |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <iostream> using namespace std; int main(void) { Stack little_stack, another_stack, funny_stack; little_stack.push(1); another_stack.push(little_stack.pop() + 1); funny_stack.push(another_stack.pop() + 2); cout << funny_stack.pop() << endl; return 0; } |
Copyright © 2026 CppDeveloper by Phạm Minh Tuấn (SHUN)