看板 C_and_CPP 關於我們 聯絡資訊
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); //也是錯誤 想請教這裡錯誤的原因為何? -- 我是麵T,哩賀 http://ppt.cc/-eS5 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 36.237.80.14 ※ 文章網址: http://www.ptt.cc/bbs/C_and_CPP/M.1411809980.A.4FB.html
carylorrk: rvalue 只能轉成 const lvalue ref 或 rvalue ref 09/27 18:13
carylorrk: 不能轉成 lvalue ref 09/27 18:13
carylorrk: 如果你的 operator 不會修改到參數,記得設 const 09/27 18:16
firose: & 的語意是要綁定到一個變數,並把結果反映給 caller。 09/27 19:58
firose: 但連續呼叫時,你傳值回來會產生暫存物件,這物件很快就消 09/27 20:00
firose: 失了,不符合 & 蘊含的意義,所以 C++ 不允許這樣的行為。 09/27 20:00
firose: 而 const & 蘊含不會修改參數的語意,所以才可以引用它。 09/27 20:03
再請教一下 double &CVector3::operator[](int index) 這邊的 & 其功用是什麼? ※ 編輯: noodleT (36.237.80.14), 09/27/2014 20:42:21
bibo9901: return a reference 09/27 21:18
bluesoul: 參數記得加上const 09/27 23:21