日志18
面向对象小结;
#include<bits/stdc++.h> using namespace std; class CPU { int rank; int fre; double v; public: CPU (int a,int b,double c):rank(a),fre(b),v(c){cout<<"CPU's constructor is called!"<<endl;} ~CPU (){cout<<"CPU's destructor is called!"<<endl;} void run (){cout<<"I am working, my rank is "<<rank<<", my frequency is "<<fre<<", my voltnumber is "<<v<<"."<<endl;} void stop(){cout<<"I stopped working!"<<endl;} }; int main(){ int a,b; double c; cin>>a>>b>>c; CPU n(a,b,c); n.run(); n.stop(); return 0; }
构造函数,用于对象初始化,无返回类型,函数名与类的名称相同,可以使用初始化列表,可结合默认形参值使用。
析构函数,用于对象使用结束后进行清除,释放空间。
两种函数在未定义时有默认函数,在定义后覆盖默认函数