c++ - 函数的返回值未被识别为左值

标签 c++ pointers reference lvalue

这是一个例子:

void foo(int*& x) {}

struct boo  
{  
  int* z;  
  int* getZ() { return z; }  
};

int main()
{
  int* y;
  foo(y);  // Fine

  boo myBoo;
  foo(myBoo.getZ());  // Won't compile

  return 0;
}

我可以通过让 boo::getZ() 返回对指针的引用来解决这个问题,但我试图了解传递给 foo() 的两个参数之间的区别。 boo::getZ() 返回的 int* 不是左值吗?如果是,为什么不呢?

最佳答案

如果 T 是一个对象类型并且 f 声明为...

T &  f();                                          f() is an lvalue
T && f();                     then                 f() is an xvalue
T    f();                                          f() is a prvalue

所以 getZ() 是一个纯右值 (T = int *),它是一个右值,而不是左值。

关于c++ - 函数的返回值未被识别为左值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24686823/

相关文章:

c++ - 获取 out_of_range : vector error for c++ but can't figure out why

c++ - 从基类到派生类的静态转换

C++ VS2010 不使用我的调试命令行参数

c++ - 创建指向另一个类的指针数组的语法是什么?

C# - 从项目的发布版本中排除单元测试

arrays - Perl - 将变量分配给引用的值

c++ - 想逐行阅读,但 fstream 只读第一行

c++ - 如果调用析构函数并将分配的内存再次用于其他对象,会发生什么情况?

c++ - 错误在 `./2' : free(): invalid pointer: 0x000000000096044c *** Aborted (core dumped)

返回对整数的引用时的 C++ 代码