gpt4 book ai didi

c++ - 为什么我在使用 &this 时会出错?

转载 作者:太空狗 更新时间:2023-10-29 20:56:23 25 4
gpt4 key购买 nike

我知道 this 指针在调用时隐式传递给成员函数。但是,当我尝试获取 this 指针的地址时(通过 &this),我得到了编译器错误“需要左值”。为什么是这样?

class st
{
int a,b;
public :
void print()
{
cout << &this; //gives lvalue required... why?

cout << this; //will print address of object.
}
}

最佳答案

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. The type of this in a member function of a class X is 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*.

强调我的

& 需要一个左值,因此您无法获得this 的地址。

关于c++ - 为什么我在使用 &this 时会出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33679419/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com