&后面接临时变量时不能取地址。
#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;
}