void fun() const{}; 、 const void fun(){}; 和void const fun(){}; 的区别?
答:const void fun(){};和void const fun(){};两个相同。
如果采用"按址传递方式"的函数返回值加const 修饰,那么函数返回值(即地址)的内容不能被修改,该返回值只能被赋给加const 修饰的同类型指针。
如果采用"按值传递方式"的函数返回值加const 修饰,由于函数会把返回值复制到外部临时的存储单元中,加const 修饰没有任何价值。
所以不要尽量不要把int fun2();写成const int fun2(); 因为没意义。
例:
#include
using namespace std;
int num=10; //全局变量
const int *fun1(){ //按址传递
return # //返回地址
}
const int fun2(){ //按值传递 //最好直接写int fun2()
return num;
}
int main()
{
const int *fun1();
// int *t1=fun1(); //错误,必须是const型
const int *t1=fun1();
// *t1=20; //按址传递,不能修改其指向变量或常量的值
cout<<"const int *fun1() :\t"<<*t1<
const int fun2(); //最好直接声明成int fun2()
int t2=fun2(); //非const变量可以更改函数返回值
const int t3=fun2();
t2 += 10; //按值传递,可以修改返回值
cout<<"const int fun2() :\t"<
return 0;
}
void fun() const{};
类的成员函数后面加 const,表明这个函数不可以对这个类对象的数据成员(准确地说是非static数据成员)作任何改变。