[英]Why am I getting an error when using &this?
I know that the this
pointer is implicitly passed to member functions when they are called. 我知道this
指针在被调用时会隐式传递给成员函数。 When I try to get the address of this
pointer (via &this
), though, I get the compiler error "lvalue required". 当我尝试获取this
指针的地址(通过&this
)时,我得到编译器错误“lvalue required”。 Why is this? 为什么是这样?
class st
{
int a,b;
public :
void print()
{
cout << &this; //gives lvalue required... why?
cout << this; //will print address of object.
}
}
this
is not an lvalue but an prvalue. this
不是一个左值,而是一个prvalue。 From [class.this]: 来自[class.this]:
In the body of a non-static (9.3) member function, the keyword this is a prvalue expression whose value is the address of the object for which the function is called. 在非静态(9.3)成员函数的主体中,关键字this是一个prvalue表达式,其值是调用该函数的对象的地址。 The type of this in a member function of a class X is X*. 类X的成员函数中的类型是X *。 If the member function is declared const, the type of this is const X*, if the member function is declared volatile, the type of this is volatile X*, and if the member function is declared const volatile, the type of this is const volatile X*. 如果成员函数声明为const,则其类型为const X *,如果成员函数声明为volatile,则其类型为volatile X *,如果成员函数声明为const volatile,则此类型为const挥发性X *。
Emphasis mine 强调我的
&
requires an lvalue
so you cannot get the address of this
. &
需要一个lvalue
,所以你不能得到的地址this
。
Because this pointer is a rvalue. 因为这个指针是一个右值。 this pointer is a constant value, it is passed to the member function like a local variable, so it's value is stored in a memory location that would become invalid when returning from that function. 这个指针是一个常量值,它像局部变量一样传递给成员函数,因此它的值存储在一个内存位置,当从该函数返回时该位置将变为无效。
Presumably you're trying to print out the values in the object. 大概你正试图打印出对象中的值。 cout doesn't know how to do this, and you have to teach it. cout不知道该怎么做,你必须教它。 cout << *this; cout << * this; might do this if cout knew how to do it, but you can teach it. 如果cout知道怎么做,可能会这样做,但你可以教它。 Here's an example that is more natural c++. 这是一个更自然的c ++示例。 (You should also consider a constructor). (您还应该考虑构造函数)。
#include <iostream>
using namespace std;
class st
{
public:
int a,b;
};
std::ostream& operator<<(std::ostream& s, const st& val)
{
return s << "a:" << val.a << " b:" << val.b ;
}
int main() {
st foo;
foo.a = 1;
foo.b = 2;
cout << "foo is " << foo << endl;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.