问题描述
考虑如下代码
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)返回的应该是一个右值,为什么可以被赋值呢??编译器没有提示错误。
问题解答
回答1:你的Code是有问题的,在我这儿.
$ g++ main.cpp --std=c++11main.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;
你的代码是例子代码吧? 你的重载运算符是错误的. 格式都写错了吧? 重载不应该是如下吗?
函数类型 X::operator 运算符(形参表){函数体}Foo operator*(const Foo &arg1, const Foo &arg2)这里面的并不代表左右值.
不太明白您的意思.
我记得右值也可以是被赋值的.如果函数返回的右值是一个引用呢?
就像下面这段代码
// 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;}回答2:
不能把“左值”、“右值”简单理解为出现在等号两边的位置。尤其是一个类对象出现在等号左边时,对象赋值实际是通过调用函数operator=完成的:
(a * b) = c ==> (a*b).operator=(c)