other questions
void fun() const{};
const void fun(){};
void const fun(){};
请问这3个有什么区别啊?
问题点数:20、回复次数:7Top
1 楼wzjall(风)回复于 2006-03-04 00:34:52 得分 0
const void fun(){};
void const fun(){};
void fun(){};
以上三个是等价的
Top
2 楼wzjall(风)回复于 2006-03-04 00:41:11 得分 0
void fun() const{};
这个应该很清楚吧!任何一本基础书上都应该有Top
3 楼cunsh(村少)回复于 2006-03-04 00:56:26 得分 0
void fun() const{};
fun是类的成员函数(不能是static的函数) . const修饰这个类的对象*this 像x.fun();中修饰那个xTop
4 楼angelo23(angelo)回复于 2006-03-04 09:30:26 得分 0
这是哪里来的题目……
const void fun(){};
void const fun(){};
这两个倒是等价,问题是这样写有意义么?Top
5 楼zh2817()回复于 2006-03-04 11:18:17 得分 0
const对象的特点与const变量类似,即不能改变const对象中的成员数据,任何修改const对象中的数据操作在编译时都会出错,只能访问对象中的const成员,但可以调用公有成员数据,一般格式如下:
<类名> const <对象名>
或const <类名> <对象名>
Top
6 楼tommy851027(努力,努力!)回复于 2006-03-04 13:09:08 得分 0
void fun() const{};
对于这个,能否举个例子啊Top
7 楼xyjchinese(春天把老婆种到地下后我就急切的盼望秋天的到来)回复于 2006-03-04 15:30:34 得分 20
const void fun(){};和void const fun(){};两个相同。
如果采用"按址传递方式"的函数返回值加const 修饰,那么函数返回值(即地址)的内容不能被修改,该返回值只能被赋给加const 修饰的同类型指针。
如果采用"按值传递方式"的函数返回值加const 修饰,由于函数会把返回值复制到外部临时的存储单元中,加const 修饰没有任何价值。
所以不要尽量不要把int fun2();写成const int fun2(); 因为没意义。
例:
#include<iostream>
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<<endl;
const int fun2(); //最好直接声明成int fun2()
int t2=fun2(); //非const变量可以更改函数返回值
const int t3=fun2();
t2 += 10; //按值传递,可以修改返回值
cout<<"const int fun2() :\t"<<t2<<endl;
return 0;
}
***********************************************************************
void fun() const{};
类的成员函数后面加 const,表明这个函数不可以对这个类对象的数据成员(准确地说是非static数据成员)作任何改变。
例:
#include<iostream>
using namespace std;
class R
{
public:
R():num1(1){}
int sum1(int a)const
{
// num1=10; //错误,不可以修改非static数据成员
return a+num1;
}
int sum2(int a)const
{
num2=2; //正确,修改static数据成员
return a+num2;
}
int sum3(int a) //没有const
{
num1=10; //正确,修改非static数据成员
num2=20; //正确,修改static数据成员
return a+num1+num2;
}
private:
int num1;
static int num2;
}t;
int R::num2=0;
int main()
{
cout<<"t.sum1(1):\t"<<t.sum1(1)<<endl;
cout<<"t.sum2(1):\t"<<t.sum2(1)<<endl;
cout<<"t.sum3(1):\t"<<t.sum3(1)<<endl;
return 0;
}Top




