怎么做网站静态布局,装饰公司资质,百度推广账户优化方案,河南一情况文章目录 一、const成员函数二、取地址运算符重载总结 一、const成员函数 1.将const修饰的成员函数称之为const成员函数#xff0c;const修饰成员函数放到成员函数参数列表的后⾯。2.const实际修饰该成员函数隐含的this指针#xff0c;表明在该成员函数中不能对类的任何成员进… 文章目录 一、const成员函数二、取地址运算符重载总结 一、const成员函数 1.将const修饰的成员函数称之为const成员函数const修饰成员函数放到成员函数参数列表的后⾯。2.const实际修饰该成员函数隐含的this指针表明在该成员函数中不能对类的任何成员进⾏修改。 在下面的日期类中我们定义了print函数。但如果我们定义const修饰的Date对象时是无法调用的这是一种权限的放大。 #includeiostream
using namespace std;
class Date
{
public:Date(int year 1, int month 1, int day 1){_year year;_month month;_day day;}// void Print(const Date* const this) constvoid Print(){cout _year - _month - _day endl;}
private:int _year;int _month;int _day;
};
int main()
{const Date d2(2024, 8, 5);d2.Print();return 0;
}这里就需要用const修饰函数。const 修饰Date类的Print成员函数Print隐含的this指针由 Date* const this 变为 const Date* const this // void Print(const Date* const this) constvoid Print() const{cout _year - _month - _day endl;}int main()
{// 这⾥⾮const对象也可以调⽤const成员函数是⼀种权限的缩⼩Date d1(2024, 7, 5);d1.Print();const Date d2(2024, 8, 5);d2.Print();return 0;
}注const修饰指向的内容和非const拷贝赋值时才涉及权限的放大和缩小 被const修饰的函数中无法再去修改成员变量
二、取地址运算符重载
取地址运算符重载分为普通取地址运算符重载和const取地址运算符重载⼀般这两个函数编译器⾃动⽣成的就可以够我们⽤了不需要去显⽰实现。除⾮⼀些很特殊的场景⽐如我们不想让别⼈取到当前类对象的地址就可以⾃⼰实现⼀份胡乱返回⼀个地址。
class Date
{
public:Date(int year 1, int month 1, int day 1){_year year;_month month;_day day;}// void Print(const Date* const this) constvoid Print() const{cout _year - _month - _day endl;}//取地址运算符重载Date* operator(){return this;// return nullptr;}const Date* operator()const{return this;// return nullptr;}private:int _year;int _month;int _day;
};总结
其实取地址运算符重载是不太需要去关注的