c++primer plus笔记

第六版


操作符重载

#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;  //error
    p1 = &b; //ok



    system("pause");
    return 0;
} 

存储持续性

自动存储持续性

函数和代码块中的变量

静态存储持续性

函数外定义或static的变量

动态存储持续性

使用new分配的内存一直存在

线程存储持续性

c++11,变量使用thread_local定义时

posted @ 2019-04-04 10:45  熊云港  阅读(182)  评论(0编辑  收藏  举报