【C++】C++ const成员函数与取地址操作符重载

发布于:2025-08-31 ⋅ 阅读:(27) ⋅ 点赞:(0)

0. 上篇

【C++】运算符重载深度解析-CSDN博客

1. const成员函数

        有时候我们定义成员函数时,为了防止成员函数修改对象,我们会在参数部分加上 const 修饰,比如:

class Date
{
public:
        Date(int year, int month, int day)
        {
                _year = year;
                _month = month;
                _day = day;
        }
        void Print()
        {
                cout << "Print()" << endl;
                cout << "year:" << _year << endl;
                cout << "month:" << _month << endl;
                cout << "day:" << _day << endl << endl;
        }
        void Func(const Date& d)
        {
                d.Print();        // 报错
        }
private:
        int _year; // 年
        int _month; // 月
        int _day; // 日
};

        但此时 d.Print() 会出现报错,因为成员函数默认含有 this 指针,调用 Func 时,相当于 d.Print(const Date* this),但 Print 函数的参数是 Print(Date* this),此时出现了权限的放大,所以出现报错。

        解决方法也很简单,把 Print 的 this 指针参数加上一个 const 就行了。

        我们将const修饰的“成员函数”称之为const成员函数,const修饰类成员函数,实际修饰该成员函数隐含的this指针,表明在该成员函数中不能对类的任何成员进行修改。

        上图中的 const 修饰的不是 this 指针本身,而是 this 指针指向的对象。

const Date* p1  -> 修饰指向的对象
Date const * p2 -> 修饰指向的对象
Date* const p3  -> 修饰指针本身

        在 const 成员函数中,不能修改成员变量,因为此时 this 指针指向的对象被 const 修饰,只读不可写。

        所以:非 const 成员函数和 const 成员函数都可以调用 const 成员函数,但是 const 成员函数不能调用非 const 成员函数。这是一个权限缩放的问题。

        那什么时候给成员函数加上 const ?

        结论:只要成员函数中不需要直接或间接修改成员变量最好都加上 const 。

2. 取地址及const取地址操作符重载

        这两个默认成员函数一般不用重新定义 ,编译器默认会生成。

class Date
{
public:
        Date* operator&()
        {
                return this;
        }
        const Date* operator&()const
        {
                return this;
        }
private:
        int _year; // 年
        int _month; // 月
        int _day; // 日
};

        这两个运算符一般不需要重载,使用编译器生成的默认取地址的重载即可,只有特殊情况,才需要重载,比如想让别人获取到指定的内容。


网站公告

今日签到

点亮在社区的每一天
去签到