> 第六版
操作符重載
#include<iostream>
using namespace std;class Time
{
public:Time(){h=m=0;}Time(int _h,int _m){h = _h;m = _m;}void show(){printf("%02d:%02d \n",h,m);}Time operator+(const Time &t){Time result;result.m = t.m + m;result.h = t.h + h + result.m/60;result.m %= 60;return result; }
private:int h;int m;
};int main(int argc,char* argv[])
{Time t(3,45);Time c(3,15);Time w = t + c;w.show();system("pause");return 0;
}
const總結
#include<iostream>
using namespace std;class Demo
{
public:int x;Demo(int _x):x(_x){}void testConstFunction(int _x) const{///錯誤,在const成員函數中,不能修改任何類成員變量x=_x;///錯誤,const成員函數不能調用非onst成員函數,因為非const成員函數可以會修改成員變量modify_x(_x);}void modify_x(int _x){x=_x;}
};int main(int argc,char* argv[])
{int a = 5;int b = 10;const int * p1 = &a; //常數據,不能通過解引用修改數據int const * p4 = &a; //常數據int * const p2 = &b; //常指針const int * const p3 = &a; //常數據和常指針// p2 = &a; //error//*p1 = 1; //errorp1 = &b; //oksystem("pause");return 0;
}
存儲持續性
自動存儲持續性
函數和代碼塊中的變量
靜態存儲持續性
函數外定義或static的變量
動態存儲持續性
使用new分配的內存一直存在
線程存儲持續性
c++11,變量使用thread_local定義時