1-23 類
阿新 • • 發佈:2019-01-24
lse urn cst clas 空間 als mes ring 賦值
類的學習
#include<iostream> #include<string> using namespace std; class Cperson { public: string Name; int *p; //構造函數與類同名,可以有參數也可以沒有參數 //無返回值 //在創建對象時一定會調用的函數 //類裏面默認一個構造函數,無參數 //構造函數的作用是給成員變量賦值 Cperson() { cout << "Cperson()" << endl; p = new int[3]; } //析構函數,反向的構造函數 //在對象被回收時,一定會被調用的函數 //在一個類裏只有一個 //省略了回收空間的操作,防止忘記 ~Cperson() { delete [ ] p; cout << "~Cperson()" << endl; } private: int m_BankPassword; public: int GetPassWord() { return m_BankPassword; } }; int main() { Cperson ps; ps.GetPassWord();return 0; }
練習1
#include<iostream> using namespace std; class CStudent { public: int id; int m_Chinese; int m_Math; CStudent(int ID, int a, int b) { id = ID; m_Chinese = a; m_Math = b; } int Average() { return (m_Chinese + m_Math) / 2; } bool IsPass() { if (m_Chinese < 60 || m_Math < 60) { return false; } return true; } }; int main() { int id; int m_ch; int m_ma; cin >> id >> m_ch >> m_ma; CStudent st1(id,m_ch,m_ma); cout << st1.Average() << endl; if (st1.IsPass()) { cout << "pass" << endl; } else { cout << "not pass" << endl; } return 0; }
練習2
#include<iostream> using namespace std; class Timer { public: int h; int m; int s; void GetTime(int hour,int minute,int second) { h = hour; m = minute; s = second; } void ShowTime() { if (h < 24 || h >= 0 || m < 60 || m >= 0 || s < 60 || s >= 0) { cout << h << ":" << m << ":" << s << endl; } } }; int main() { Timer st; st.GetTime(23, 34, 56); st.ShowTime(); }
1-23 類