返回值为引用的一点测试

最近做多人视频时设计了一个简单的类,但是简单的类也很能说明问题,也再次说明有些基础知识还是理解得不够深刻,刚写了个测试程序以便日后查阅,主要是关于返回值为引用类型时的一点测试:

#include <iostream>
using namespace std;

class CConstRef
{
public:
CConstRef(int iA):m_iA(iA)
{
}
const int& GetA()const
{
return m_iA;
}
int& GetA()
{
return m_iA;
}
void PrintAddress()const
{
cout<<"Address of m_iA = "<<&m_iA<<endl;
}
private:
int m_iA;
};

int main(int argc, char* argv[])
{
//常量对象
const CConstRef cCA(8);
//非常量对象
CConstRef CA(9);
//////////////////////////////////////////////////////////////////////////
//注意下面的调用都是返回对象cCA的成员m_iA的引用,且此引用都是用来初始化另一引用
//因此地址都相同
//调用int& GetA()
int& ra = CA.GetA();
CA.PrintAddress();
cout<<"Address of ra = "<<&ra<<endl;
ra = 3;
cout<<"Now the CA.m_iA = "<<CA.GetA()<<endl;

//调用int& GetA()
const int& ra1 = CA.GetA();
cout<<"Address of ra1 = "<<&ra1<<endl;
//////////////////////////////////////////////////////////////////////////
//调用int& GetA()
int va = CA.GetA();
CA.PrintAddress();
cout<<"Address of va = "<<&va<<endl;
va = 3;
cout<<"Now the CA.m_iA = "<<CA.GetA()<<endl;

//调用int& GetA()
const int va1 = CA.GetA();
cout<<"Address of va1 = "<<&va1<<endl;
//////////////////////////////////////////////////////////////////////////
//下面的rb就是cCA.m_iA
const int& rb = cCA.GetA();

cCA.PrintAddress();
cout<<"Address of rb = "<<&rb<<endl;

/*
error: invalid initialization of reference of type 'int&' from expression of type 'const int'
上面的错误时G++提示的,这么说来其实编译器给我们返回的是const int而不是const int&
*/
// int& rb1 = cCA.GetA();

//下面的的vb和vb1都是是cCA.m_iA的一个副本
const int vb = cCA.GetA();
cout<<"Address of vb = "<<&vb<<endl;

int vb1 = cCA.GetA();
cout<<"Address of vb1 = "<<&vb1<<endl;
vb1 = 10;

cout<<"Now the cCA.m_iA = "<<cCA.GetA()<<endl;

return 0;
}

下面是在MinGW的G++下输出的结果

返回引用

 

 

路路漫漫其修远兮,吾将上下而求索!