gpt4 book ai didi

c++ - 我可以分配给成员访问运算符的返回值吗?

转载 作者:太空宇宙 更新时间:2023-11-04 15:30:26 26 4
gpt4 key购买 nike

我读到成员访问运算符点运算符 . 和箭头运算符 -> 返回值:

The arrow operator requires a pointer operand and yields an lvalue. The dot operator yields an lvalue if the object from which the member is fetched is an lvalue; otherwise the result is an rvalue.

这是来自 C++ Primer 5 版。

所以我想只要非 const 左值是它们表达式的返回值,我就可以分配一个值,例如:

struct foo {
int x_;
const int y_ = 17; ;
void bar() { cout << "bar()" << endl;}
}f, *pf;

pf = &f;

(pf->bar()) = 75; // error
cout << f.x_ << endl;
(f.bar()) = 12;// error
(f.x_) = 23;
cout << "f_x: " << f.x_ << endl;
(pf->y_) = 34;// error

我对给箭头运算符的返回值赋值感到困惑。上面说 -> 总是返回一个左值,但是如果我尝试分配给那个值它会失败。

  • 谁能给我解释一下 C++ 书中的上述段落。谢谢。

最佳答案

Above it is said that -> always returns an lvalue but it fails if I try to assign to that value.

这是关于成员变量,而不是函数。 bar 返回 void 所以你永远不能分配给它。 x_ 有效,因为它为您提供了一个整数左值表达式。 y_ 失败,因为它是 const,您不能分配给 const 变量。

所以,在

foo bar;
foo* f = &bar;
f->x_;
f->y_;

两个成员访问都产生一个左值表达式。在

foo f;
f.x_;
f.y_;

因为 f 是一个左值,所以你又得到了左值。然而,在

foo{}.x_;
foo{}.y_;

两个成员访问都是右值,因为 foo{} 是右值。

关于c++ - 我可以分配给成员访问运算符的返回值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55031297/

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