[问题] class 没办法做连续的四则运算

楼主: noodleT (面T)   2014-09-27 17:26:17
class CVector3{
private:
double e[3];
public:
friend CVector3 operator *(CVector3 &a, double p); //向量*常数
friend CVector3 operator +(CVector3 &a, CVector3 &b);
double &operator[](int);//元素操作
};
double &CVector3::operator[](int index){
if (index < 3 && index >= 0){
return e[index];
}
else{
static double err = 0.0;
return err;
}
}
和此网站:
http://nknucc.nknu.edu.tw/~jwu/c/cpgch14.htm
的例7相比,我多了 &operator[] 的操作
目的是想要较方便的存取 e[0~2]
但却造成我没办法做连续的向量运算,如:
CVector3 a1,a2,b(1,2,3),c(4,5,6);//建构时可写入初始值,上面程式码省略
a1=b+c; //这样OK
a1=b*2.0; //OK
a2=b+c*2.0; //错误
a2=b+(c*2.0); //也是错误
想请教这里错误的原因为何?
作者: carylorrk (carylorrk)   2014-09-27 18:13:00
rvalue 只能转成 const lvalue ref 或 rvalue ref不能转成 lvalue ref如果你的 operator 不会修改到参数,记得设 const
作者: firose (guest也是也是也是也是也)   2014-09-27 19:58:00
& 的语意是要绑定到一个变量,并把结果反映给 caller。但连续呼叫时,你传值回来会产生暂存物件,这物件很快就消失了,不符合 & 蕴含的意义,所以 C++ 不允许这样的行为。而 const & 蕴含不会修改参数的语意,所以才可以引用它。
作者: bibo9901 (function(){})()   2014-09-27 21:18:00
return a reference
作者: bluesoul (忙死你老爸)   2014-09-27 23:21:00
参数记得加上const

Links booklink

Contact Us: admin [ a t ] ucptt.com