const总结三 之 常量函数返回值

先贴代码:

class Return
{
public:
	Return(void);
	~Return(void);

	const int getInt();
	const int* getIntPointL();
	int* const getIntPointR();
};

 

#include "Return.h"


Return::Return(void)
{
}


Return::~Return(void)
{
}


const int Return::getInt()
{
	return 10;
}
const int* Return::getIntPointL()
{
	int* i = new int(10);
	return i;
}
int* const Return::getIntPointR()
{
	int* i = new int(10);
	return i;
}

 

main入口:

#include <iostream>
using namespace std;

#include "Return.h"

void main()
{
	Return* ret = new Return();
	
	//常量返回值可以复制给非常量
	int rInt = ret->getInt();
	//常量返回值可以复制给常量
	const int rcInt = ret->getInt();

	//int* pIntL = ret->getIntPointL();//error C2440: “初始化”: 无法从“const int *”转换为“int *”
	/************************************************************************/
	/*    const int *的内容是不能修改的,如果现在赋值给pIntL,而pIntL又不是
		常量,那么可以通过pIntL去修改内容。那么返回的const int *也就没意义了。
	/************************************************************************/
	const int* pIntL = ret->getIntPointL();

	int* pIntR = ret->getIntPointR();
	/************************************************************************/
	/* 这里的int* const 居然可以赋值给int*,那我这里觉得返回int* const 没有什么意义
	/************************************************************************/
	int* const pIntRx = ret->getIntPointR();
}

 总结与疑问:

在函数返回的时候,采用常量,就可以保护返回的内容不受修改,如上例的返回 const int * 。它保护了返回的指针所指向的内容不受修改。

但是,返回 int* const ,其用意就是保护返回的指针值不受到修改,但是它居然可以复制给int*。我觉得返回int* const 的意义就是返回值必须赋值给int* const 的变量,这样程序员在编码过程或者在编译的时候,就必须保证这个指针值必须是常量,不可修改,才能通过编译。那么返回int* const 才有意义。

这方面不是很懂,希望有人就这个问题发表一下看法,让我也能学习一下。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值