一、前言
1)错误起源
自己看C++教学视频到静态函数。
地址:https://www.imooc.com/learn/477
发现提到了static修饰的静态成员函数,函数中没有this指针。
而之前讲过的const修饰的常成员函数,const修饰的就是this指针。
二者相加,就发现这个错误。
class Airplane
{
public:
static int ApNum;
public:
Airplane() { ApNum++; }
static int GetApNum() const//const报错,因为没有this指针。
{
return ApNum;
}
};
2)那怎么样才不会报错呢?
class Airplane
{
public:
static int ApNum;
public:
Airplane() { ApNum++; }
static const int GetApNum()//不报错。
{
return ApNum;
}
};
好的,这样就不会报错了。但是这还是const修饰的常成员函数么?不是说static修饰的静态成员函数没有this指针么?参见下面代码。
static int GetApNum()
{
this->ApNum = 10;//没有this指针,语法报错。
return ApNum;
}
那static const int GetApNum()函数里面const修饰的到底是什么?哪来的this指针?
3)结论:static const int GetApNum()不是常成员函数。const修饰的不是this指针,是函数返回值。
参考博客:
1:https://www.cnblogs.com/azbane/p/7266747.html
2:https://www.cnblogs.com/doker/p/11051175.html
3:https://www.cnblogs.com/narjaja/p/9300525.html
二、const语法总结
基本内容和参考博客相同,下面自己用最简单的语言总结。
const修饰的不仅仅是变量,还可以是返回值和函数本身。
1)const来源单词constant。意思是不变。
不论修饰什么,意思就是修饰的内容不会改变。
/*const修饰的值得权限为,只读不可写*/
const int X = 10;//变量X为常量,后续代码不可以修改X的值。
const int GetX(){ return X;}//函数为普通函数。const修饰X的返回值,返回值不可修改。
最后是常成员函数
class ShowX
{
int X = 0;
/*函数GetX()为常函数,函数中不可修改数据成员。*/
int GetX() const
{
X = 10;//报错,常函数不可以修改数据成员。
return X;
}
}