博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

C/CPP-类的6个重要成员函数

Posted on 2023-03-13 09:38  乔55  阅读(7)  评论(0编辑  收藏  举报

类的6个重要成员函数

class Test
{
private:
    int data;
public:
    // 1、普通构造函数
    Test(int d = 0) :data(d){}

    // 2、拷贝构造函数
    Test(const Test& that)
    {
        data = that.data;
    }

    // 3、重载等号操作符
    Test& operator=(const Test& that)
    {
        if (this != &that)
        {
            data = that.data;
        }
        return *this;
    }

    // 4、析构函数
    ~Test(){ }

    // 5、重载取地址操作符
    // Test* ptr = &t;  相当于:Test* ptr = t.operator&();
    Test* operator&()
    {
        return this;
    }

    // 6、常对象取地址,重载
    // const Test t; const Test* ptr = &t; 对常对象进行取地址
    const Test* operator&()const
    {
        return this;
    }
};