[問題] 朋友函式和const參照引數
開發平台(Platform): (Ex: Win10, Linux, ...)
Win10
編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出)
VC++
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
無
問題(Question):
大家好! 小弟是C++的新手
我們都知道 int& q=5; 的寫法是錯誤的
如果要達成上述的目標
必須宣告成 const int& q=5;
如今我要做一個複數類別
並實作運算子多載
例如:
Complex operator+(const Complex& x){
...
}
然後宣告三個物件
Complex x,y,z;
z=x+y //ok
z=x+5.0 //ok
z=5.0+x //Wrong
所知道正確寫法會被改為
friend Complex operator+(const Complex& x,const Complex& y){}
才能達成!
我比較好奇的是friend到底真正改變的是甚麼?
我看過了一些網路資料但是 還是有點不太清楚
最後
為什麼一定要把引數宣告成const?
這是預防甚麼情況呢?
我的想法大概是如下:
Complex a,b;
a=b+5.0
為的是因為5.0是常數
所以一定要宣告成const才能接收
我覺得觀念不是很清楚
有沒有更詳盡的講法@@
感謝各位
餵入的資料(Input):
無
預期的正確結果(Expected Output):
無
錯誤結果(Wrong Output):
無
程式碼(Code):(請善用置底文網頁, 記得排版)
補充說明(Supplement):
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 118.163.199.186
※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1482807509.A.2DE.html
→
12/27 11:55, , 1F
12/27 11:55, 1F
→
12/27 13:10, , 2F
12/27 13:10, 2F
→
12/27 13:10, , 3F
12/27 13:10, 3F
→
12/27 13:11, , 4F
12/27 13:11, 4F
→
12/27 13:11, , 5F
12/27 13:11, 5F
→
12/27 15:25, , 6F
12/27 15:25, 6F
→
12/27 15:32, , 7F
12/27 15:32, 7F
→
12/27 15:32, , 8F
12/27 15:32, 8F
→
12/27 15:32, , 9F
12/27 15:32, 9F
→
12/27 15:37, , 10F
12/27 15:37, 10F
→
12/27 15:37, , 11F
12/27 15:37, 11F
→
12/27 15:37, , 12F
12/27 15:37, 12F
推
12/27 15:39, , 13F
12/27 15:39, 13F
→
12/27 15:40, , 14F
12/27 15:40, 14F
→
12/27 15:40, , 15F
12/27 15:40, 15F
→
12/27 15:41, , 16F
12/27 15:41, 16F
→
12/27 15:41, , 17F
12/27 15:41, 17F
→
12/28 13:44, , 18F
12/28 13:44, 18F
→
12/28 13:44, , 19F
12/28 13:44, 19F
→
12/29 01:10, , 20F
12/29 01:10, 20F