void func() const:
这种类型的const必须和类对象联系在一起,即存在this指针。下面是错误的使用:
int func() const //error编译无法通过
{
int a = 10;
return a;
}
int main(int argc, char *argv[])
{
int a;
a = func();
a = 20;
cout<<a<<endl;
return 0;
}
实际上,函数体形参后跟着的const关键字是特别修饰隐式this形参的:
隐式this形参:
class student
{
public:
int func() const;
private:
int std_count;
};
int student::func() const
{
int a = 10;
return a;
}
int main(int argc, char *argv[])
{
int a;
student sd;
a = sd.func();
a = 20;
cout<<a<<endl;
return 0;
}
在上述代码中,在调用 sd.func(); 时,其实被编译器重写成 student::func(&sd), &sd即可理解为this指针指向的地址; 而关键字const的作用则是修饰该对象不可修改,this指针指向的对象(sd)不可被修改。
int student::func() const
{
int a = 10;
this->std_count = 10;
return a;
}
如上代码尝试修改const修饰下对象的std_count属性,编译将报错:error : l-value specifies const object
const int func() :
const用于修饰func函数的返回值,其返回值是const类型。
char arr[] = "fefsdf";
const char* func()
{
return arr;
}
int main(int argc, char *argv[])
{
char* arr1;
arr1 = func();
arr1 = "feasdf"; //error: '=' : cannot convert from 'const char *' to 'char *'
cout<<arr1<<endl;
return 0;
}
注意:如果函数返回值采用“值传递方式”,由于函数会把返回值复制到外部临时的存储单元中,加const 修饰没有任何价值。
例如不要把函数int GetInt(void) 写成const int GetInt(void)。
int func(const int):
修饰形参为const类型。