错误 C2102 “&”要求左值

文章讨论了在C++编程中,当使用成员函数`get()`返回对象时,尝试对返回的对象取地址会引发错误。原因在于`get()`返回的是一个临时对象的副本,而不是原始对象的引用。因此,不能直接比较其地址。解决方法是先将`get()`返回的对象赋值给一个新的对象,然后比较这两个对象的地址。
摘要由CSDN通过智能技术生成

&后面接临时变量时不能取地址。

#include <iostream>
#include <string>
using namespace std;

class A
{
public:
	A get()
	{
		return *this; //拷贝一个新的对象(一样但不是同一个)
	}
	int m_a;
};

int main()
{
	A a;//创建一个对象
	a.m_a = 2;
	if (a.m_a == a.get().m_a)
	{
		cout << a.m_a << "  " << a.get().m_a << endl;
	}
	else
	{
		cout << "oo" << endl;
	}
	if(&a==&a.get()) //报错: error C2102: “&”要求左值
	{
		cout << "the same address" << endl;
	}
	else
	{
		cout << "no same" << endl;
	}
	return 0;
}

修改:

#include <iostream>
#include <string>
using namespace std;

class A
{
public:
	A get()
	{
		return *this; //拷贝一个新的对象(一样但不是同一个)
	}
	int m_a;
};

int main()
{
	A a;//创建一个对象
	a.m_a = 2;
	if (a.m_a == a.get().m_a)
	{
		cout << a.m_a << "  " << a.get().m_a << endl;
	}
	else
	{
		cout << "oo" << endl;
	}
//修改后
	A b = a.get();
	if(&a==&b)
	{
		cout << "the same address" << endl;
	}
	else
	{
		cout << "no same" << endl;
	}
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值