/*
类型是否匹配,&不修饰类型,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;
}
类成员函数和函数返回值的结合使用探究
最新推荐文章于 2024-04-11 08:00:24 发布