gpt4 book ai didi

c++ - 函数将结构返回为 LValue

转载 作者:IT老高 更新时间:2023-10-28 13:00:38 27 4
gpt4 key购买 nike

在下面的代码片段中,为什么行 o.margin() = m; 编译没有错误?它很容易得到警告,因为它几乎总是一个错误。我实际上会认为这是一个错误,因为它会将 R 值放在赋值的左侧。

#include <iostream>

struct Margin
{
Margin(int val=0) : val(val) {};
int val;
};

struct Option
{
Margin m;
int z=0;

Margin margin()const { return m; }
int zoomLevel() { return z; }
};


int main()
{
Option o;
std::cout << "Margin is: "<< o.margin().val << std::endl;

Margin m = { 3 };

// The following line is a no-op, which generates no warning:
o.margin() = m;

// The following line is an error
// GCC 4.9.0: error: lvalue required as left operand of assignment
// clang 3.8: error: expression is not assignable
// MSVC 2015: error C2106: '=': left operand must be l-value
o.zoomLevel() = 2;

std::cout << "Margin is: "<< o.margin().val << std::endl;

return 0;
}

输出:

Margin is: 0
Margin is: 0

最佳答案

您可以修改类类型的返回类型(通过在其上调用非 const 方法):

3.10/5 来自 n4140

5 An lvalue for an object is necessary in order to modify the object except that an rvalue of class type can also be used to modify its referent under certain circumstances. [ Example: a member function called for an object (9.3) can modify the object. —end example ]

你的代码:

o.margin() = m;

其实和

是一样的
o.margin().operator=( Margin(m) );

所以调用非 const 方法,如果你把它改成:

o.margin().val = m;

那么你会得到一个错误。

另一方面:

o.zoomLevel() = 2;

zoomLevel() 返回非类类型,所以不能修改。

关于c++ - 函数将结构返回为 LValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37544600/

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