作者:
LPH66 (-6.2598534e+18f)
2014-05-25 20:36:48※ 引述《putumaxally (putumaxally)》之銘言:
: 大致上都能夠理解 (汗
: 感謝大大讓我知道我對陣列的概念一直是錯的,之前在板上的文章看到 decay
: 都直接自動無視,一直堅持著陣列等同於指標(只是它永遠指向第一個元素)
: 我之前有寫過這種程式 http://pastebin.com/fv9DVKNW
: 這樣是合法的嗎(好像有看到置底的動畫說多維陣列不應該這樣用
如果是嚴格符合標準的話這個確實不行
(簡單的理由是陣列存取超出範圍, 但這裡還有一個 aliasing 的問題在)
: reference parameter 的問題主要是看到這一篇文章 http://ppt.cc/R~t8
: "However, this statement will not even compile because every overloaded
: operator function must either be a member of a class, or have a parameter
: of type T, T &, or T const &, where T is a class or enumeration type.
: So in this particular case, using a reference is the only way to do it."
: 對於他說的只能用 reference 當參數,一直無法知道為什麼,不過剛剛
: google 了一下,看到類似的文章(貌似是同一個作者),
: "Every overloaded operator function must either be a member of a class,
: or have a parameter of type T, T &, or T const &, where T is a class or
: enumeration type. In other words, every overloaded operator must accept
: an argument of a class or enumeration type. A pointer, even to an object
: of class or enumeration type, doesn't count."
: 因為第一個參數必須讓 compiler 知道我是寫誰的運算子多載,而指標不算(被排擠?
: 所以 enum 的運算子多載第一個參數一定要用 enum type 或 reference 對吧。
: 硬要用指標的話就會跑出這種奇怪的程式碼
: day operator+(day d1, day* d2); => d1 + &d2
: PS.每次碰到C++的問題就會有一種感想,如果C是池塘,那C++就是大海,無窮無盡...
: 學校的老師(機械系)也不太敢教 C++,直接教 C#
其實問題並不只在左邊 也不限制在指標
這裡的規定是你不能對所有運算元都是 primitive type 的 operator 做 overloading
例如你不能定義 operator + (int, int) 或 operator ! (int)
但是你可以定義 operator + (FooClass, int)
operator + (int, FooClass)
operator ! (FooClass)
FooClass::operator + (int)
FooClass::operator ! ()
因為這些式子都有至少一個運算元不是 primitive type
指標本身也是一種 primitive type, 所以也受到這個限制
也就是說你不能定義 operator + (int *, int)
operator + (int *, int *)
operator + (FooClass*, int)
但你可以定義 operator + (FooClass, int *)
operator + (FooEnum&, FooEnum*)
等等
這個限制並不是「operator 的第一個參數得要非 primitive」
而是「operator 至少要有一個參數非 primitive」
我上篇回文的例子就有舉了 operator == (const char *, const string &)
這就是個左邊是指標, 右邊是 std::string 的參考的一個 overloaded operator
因為第二個參數不是 primitive 所以這種 overload 是允許的
它會在 "someCString" == someStringObject 這個時候被呼叫到
另外要注意到的是 overloaded operator 編譯器會換成對應的函式呼叫
也就是說你在 operator 的兩邊寫上什麼 傳進函式的就是什麼
因此如果硬要定成指標 像是你上面寫的 operator + (day d1, day* d2)
那就必須要用 d1 + &d2 這樣才會呼叫到那個函式