赞
踩
const修饰类的成员函数
将const修饰的类成员函数称之为const成员函数.
const修饰类的成员函数, 实际上修饰的是该成员函数隐含的this指针, 这表明在该成员函数中不能对类的任何成员进行修改.
看下面这段代码:
#include <iostream> using namespace std; class Date { int m_year; int m_month; int m_day; public: void display() { cout << "display ()" << endl; cout << "year:" << m_year << endl; cout << "month:" << m_month << endl; cout << "day:" << m_day << endl << endl; } void display() const { cout << "display () const" << endl; cout << "year:" << m_year << endl; cout << "month:" << m_month << endl; cout << "day:" << m_day << endl << endl; } }; int main() { Date d1; d1.display(); const Date d2; d2.display(); system("pause"); return 0; }
总结
取地址及const取地址操作符重载
这两个默认成员函数一般不用重定义, 编译器会默认生成
class Date
{
int m_year;
int m_month;
int m_day;
public:
Date * operator &()
{
return this;
}
const Date * operator &() const
{
return this;
}
};
这两个运算符一般不需要重载, 使用编译器生成的默认取地址的重载即可, 只有特殊情况, 才需要重载, 比如不想让其他用户获取到指定内容.
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。