Re: [問題] template語法問題
※ 引述《Cloud (抓不住...)》之銘言:
: 下述是我學習C#的疑問
: public class TreeNode<ItemType>
: {
: public ItemType m_Value; // member
: public TreeNode(ItemType val){m_Value = val; } // Ctor
: public void comapre(ItemType v )
: {
: if( m_Value > v ) // 編譯錯誤,這裡的值會無法比較,即使
: // ItemType為int
: {
: // some operation
: }
: }
: }
: 請問該如何實做?? 是否需要ICompariable ??
IComparable是用來排序的,跟你的寫法無關,因為你直接用>符號來比較。
你的ItemType是不是Int不重要。
重要的是如果你要自定類別,那麼Operator是一定要重寫的。
不然「int > int」這樣編譯器看得懂,「科科 > 科科」就看不懂了,
因為你沒有定義自定類別要怎麼比大小。
但是重寫 > 的語法我忘了,科科
public static bool operator > (科科 a, 科科 b)
{
return a.value > b.value;
}
我憑印象亂寫的,請查書確定一下。
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 118.168.20.113
推
02/24 22:03, , 1F
02/24 22:03, 1F
→
02/24 22:04, , 2F
02/24 22:04, 2F
討論串 (同標題文章)