类成员函数和函数返回值的结合使用探究

/*
类型是否匹配,&不修饰类型,const修饰指针的时候参与类型
返回是值的话,内置类型的话就是寄存器带出都是常量数字不能取地址,没有内存。
返回的是指针的话都是一个立即数常量数字,需要用常引用
返回的是引用的话,返回return后面的表达式的地址,可以用指针和引用接收都是可以
*/
#include<iostream>
#include<typeinfo>
using namespace std;
class Test
{
public:
	Test(int data=10):mptr(new int(data)){}
	//1返回值
	int GetInt(){ return *mptr; }
	int GetInt()const{ return *mptr; }

	//2返回引用
	int& GetIntRef(){ return *mptr; }
	int& GetIntRef()const{ return *mptr; }

	//3返回指针
	int* GetPtr(){ return mptr; }
	int* GetPtr()const{ return mptr; }//只是把mptr对应的值返回出去,不是返回常量mptr的地址
	 
	//4返回指针的引用
	int*& GetPtrRef(){ return mptr; }//返回的是mptr的地址
	int*& GetPtrRef()const{ return mptr; }//是返回常量mptr的地址,返回引用隐式取地址,返回后是int*const*类型
	
private:
	int *mptr;
};
int main4()
{
	Test t1;
	const Test t2;

   	 int *a1 = t1.GetPtrRef();
	 int *&b1 = t1.GetPtrRef();   
	 const int const*&c1 = t1.GetPtrRef();//返回的类型是int **,不匹配 错误
								//改正方法1、int* const &c1=t1.GetPtrRef()
								//改正方法2、const int* const &c1=t1.GetPtrRef()
	int *a2 = t2.GetPtrRef();
	int *&b2 = t2.GetPtrRef();   
	const int *&c2 = t2.GetPtrRef();//返回的类型是Int *const * 错误,类型不匹配
										//改正方法1、int* const &c1=t1.GetPtrRef()
										//改正方法2、const int* const &c1=t1.GetPtrRef()
	return 0;
}

int main3()
{
	Test t1;
	const Test t2;

	int *a1 = t1.GetPtr();
	int *&b1 = t1.GetPtr();   //错误,返回的是mptr常量没有内存。改正:int * const &b1 用临时量引用
	const int *&c1 = t1.GetPtr();//错误,返回的是mptr常量没有内存。const int *const&c1 = t1.GetPtr()常引用

	int *a2 = t2.GetPtr();
	int *&b2 = t2.GetPtr();   //错误,返回的是常量的地址int *const *没有内存。改正:int * const &b1 用临时量引用
	const int *&c2 = t2.GetPtr();//错误,返回的是常量的地址int *const *没有内存 。改正:int * const &b1 用临时量引用

	return 0;
}

int main2()
{
	Test t1;
	const Test t2;

	int a1 = t1.GetIntRef();
	int &b1 = t1.GetIntRef();   
	const int &c1 = t1.GetIntRef();

	int a2 = t2.GetIntRef();
	int &b2 = t2.GetIntRef();     
	const int &c2 = t2.GetIntRef();

	return 0;
}
int main1()
{
	Test t1;
	const Test t2;
	
	int a1 = t1.GetInt();
	int &b1 = t1.GetInt(); //返回的值寄存器带出无法取地址,不能初始化引用。错误表达式
							//更正方法,使用const 常引用,编译器使用临时量引用
	const int &c1 = t1.GetInt();

	int a2 = t2.GetInt();
	int &b2 = t2.GetInt(); //返回的值寄存器带出无法取地址,不能初始化引用。错误表达式
							//更正方法,使用const int &常引用,编译器使用临时量引用
	const int &c2 = t2.GetInt();

	return 0;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值