const 修饰成员函数
在成员函数后面加const ,const 修饰this指针所指向的对象,也就是保证调用这个const成员函数的对象在函数内不会被改变。
class Date
{
public:
Date()
{}
void show()
{
cout << "show()" << endl;
cout << _year << "-" << _month << "-" << _day << endl;
}
void show() const//const修饰this指针相当于void show(const Date* this)
{
cout<<"show() const"<<endl;
cout << _year << "-" << _month << "-" << _day << endl;
}
private:
int _year;
int _month;
int _day;
};
void TestDate()
{
Date d;
d.show();
const Date d1;
d1.show();
}
执行结果为:
const权限只可以缩小。
那么思考以下几种场景
1 . const 对象可以调用非const 成员函数和const 成员函数吗?//可以
2 . 非const 对象可以调用非const 成员函数和const 成员函数吗?//不可
3 . const 成员函数内可以调用其它的const 成员函数非const 成员函数吗?//可以
4 . 非const 成员函数内可以调用其它的const 成员函数非const 成员函数吗?//不可
在同一类中。在一成员函数中可以调用任一成员函数。
inline(内联)函数
以inline修饰的函数叫做内联函数,编译时C++编译器会调用内联函数的地方展开,没有函数压栈的开销,内联函数提升程序运行的效率。
注意:
- inline函数以空间换时间,省区调用函数的开销,代码很长或者有循环/递归的的函数不适宜使用内联。
- inline对于编译器而言只是一个建议。编译器会自动优化,如果定义为inline的函数体内有循环/递归等等,编译器优化时会忽略掉内联。
- inline必须函数定义放在一起,才能成为内联函数,仅将其放在声明前不起作用。
- 定义在类内的成员函数默认为内联函数。
class Date
{
public:
void func()//定义在类内默认为内联函数
{}
void show();//声明
private:
int _year;
int _month;
int _day;
};
inline void Date::show()//成员函数定义为内联
{
cout << _year << "