c++ - 关于左右值的疑问?
PHP中文网
PHP中文网 2017-04-17 15:16:02
0
2
427

考虑如下代码

class Foo
{
public:
    int x, y;
};
Foo operator*(const Foo &lhs, const Foo &rhs)
{
    Foo ret;
    return ret;
}

int main()
{
    Foo a, b, c;
    (a * b) = c;
    return 0;
}

operator*(a, b)返回的应该是一个右值,为什么可以被赋值呢??编译器没有提示错误。

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(2)
洪涛

There is a problem with your Code, it’s mine.

$ g++ main.cpp --std=c++11
main.cpp:10:49: error: ‘Foo Foo::operator*(const Foo&, const Foo&)’ must take either zero or one argument
     Foo operator*(const Foo &lhs, const Foo &rhs)
                                                 ^
main.cpp: In function ‘int main()’:
main.cpp:20:8: error: no match for ‘operator*’ (operand types are ‘Foo’ and ‘Foo’)
     (a * b) = c;

Is your code an example code? Your overloaded operator is wrong. Is the format wrong? Shouldn’t the overloaded be as follows?

函数类型 X::operator 运算符(形参表)
{
函数体
}

Foo operator*(const Foo &arg1, const Foo &arg2)
这里面的并不代表左右值.

I don’t quite understand what you mean.

I remember that rvalues ​​can also be assigned.What if the rvalue returned by the function is a reference?

Just like the following code

// array::front
#include <iostream>
#include <array>

int main ()
{
  std::array<int,3> myarray = {2, 16, 77};

  std::cout << "front is: " << myarray.front() << std::endl;   // 2
  std::cout << "back is: " << myarray.back() << std::endl;     // 77

  myarray.front() = 100; ///???? 

  std::cout << "myarray now contains:";
  for ( int& x : myarray ) std::cout << ' ' << x;

  std::cout << '\n';

  return 0;
}
刘奇

We cannot simply understand "lvalue" and "rvalue" as appearing on both sides of the equal sign. Especially when a class object appears on the left side of the equal sign, the object assignment is actually completed by calling the function operator=:

(a * b) = c ==> (a*b).operator=(c)

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template