C++之函数和const

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类型。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值