方法调用的行为异常

方法调用的行为异常

本文介绍了方法调用的行为异常,类似于l值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以解释为什么此代码编译的原因:

Can anybody explain why this code compiles:

typedef struct longlong
{
  unsigned long low;
  long high;
}
longlong;

typedef longlong Foo;

struct FooStruct
{
private:
  Foo bar;

public:
  void SetBar(Foo m)
  {
    bar = m;
  }

  Foo GetBar()
  {
    return bar;
  }
};

int main()
{
  FooStruct f;
  Foo m1 = { 1,1 };
  Foo m2 = { 2,2 };
  f.SetBar(m1);
  f.GetBar() = m2;     // Here I'd expect an error such as
                       // "error: lvalue required as left operand of assignment"
}

我希望编译失败并出现错误:在 f.GetBar()= m2; 行上需要左值作为赋值的左操作数,因为IMO f.GetBar()不是l值,但可以编译,并且 f.GetBar()= m2; 是NOP.

I expected the compilation to fail with error: lvalue required as left operand of assignment on line f.GetBar() = m2; because IMO f.GetBar() is not an l-value, but it compiles seemlessly and f.GetBar() = m2; is a NOP.

另一方面,如果我将 typedef longlong Foo; 替换为 typedef long Foo; ,则前面提到的行将无法编译,并且会出现预期的错误.

On the other hand if I replace the typedef longlong Foo; by typedef long Foo;, the line mentioned before won't compile and I get the expected error.

我在重构一些旧代码时遇到了这个问题.这个问题中的代码除了说明这个问题外没有其他用途.

I came along this issue while refactoring some old code. The code in this question has no purpose other than to illustrate this issue.

推荐答案

此行为的原因已在其他答案中进行了描述.

Reasons for this behavior were described in other answers.

避免这种行为的一种方法是使用 const 限定返回类型:

One way to avoid this behavior would be qualifying your return type with const:

struct FooStruct
{
    ...
    const Foo GetBar() {return bar;}
};

您不能为 const 对象分配值,因此编译器会抱怨.

You cannot assign values to const objects, so the compiler will complain.

这篇关于方法调用的行为异常,类似于l值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 08:45