[問題] 在class內部call functions

看板C_and_CPP (C/C++)作者 (steve)時間14年前 (2011/12/25 22:39), 編輯推噓1(1013)
留言14則, 3人參與, 最新討論串1/1
大家好我又來問問題了 我想問的是有辦法在class呼叫function 比如說我寫了一個class叫做 A 有一個member function叫做f1 public : A f1(A); 那要是我寫第二個function A f2(int); 我想在裡面call f1要怎麼做到 其實我是想要在乘法裡面直接call加法 做大數的乘法 也就是我有一個class HugeInteger public: HugeInteger add(HugeInteger); HugeInteger multiply(int); 我的multiply只要可以接受整數就可以了 不需要接受大數字 那現在我想要在裡面call add的function 我寫程式碼 HugeInteger HugeInteger::multiply(int N) { for(int i=0;i<N;i++) this->add(??) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 這邊要是想要call add的話是要用this 這個pointer嗎? 那後面的引數我想 要加自己要怎麼辦到 } 問題好多部分 麻煩各位大哥了! -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.34.202.142

12/25 23:03, , 1F
做法有很多,可以 overload static_cast<int>
12/25 23:03, 1F

12/25 23:03, , 2F
也可以寫個成員函數 int to_int() const ;
12/25 23:03, 2F

12/25 23:04, , 3F
然後該行這樣呼叫就好了: add( to_int() );
12/25 23:04, 3F

12/25 23:05, , 4F
add() 跟 to_int() 都不需要 this pointer
12/25 23:05, 4F

12/25 23:06, , 5F
不過這樣數字是以指數成長XD 應該不是你要的
12/25 23:06, 5F

12/25 23:06, , 6F
int begin = to_int; for(...){ add( begin ) }
12/25 23:06, 6F

12/25 23:07, , 7F
另外存起來就好了吧,以上
12/25 23:07, 7F
OK嘗試中 謝謝大大 ※ 編輯: steve1012 來自: 114.34.202.142 (12/25 23:22)

12/26 03:52, , 8F
不就直接add(*this)就好了嗎? 還是我漏了甚麼?
12/26 03:52, 8F

12/26 03:54, , 9F
不過這樣做的話你需要多寫個copy constructor
12/26 03:54, 9F

12/26 13:24, , 10F
這設計感覺有問題 N*3 很可能會變成 N^3 喔...
12/26 13:24, 10F

12/26 13:25, , 11F
this->add(*this) 每跑一次就變兩倍了XD
12/26 13:25, 11F

12/26 16:41, , 12F
喔原來,那就先把*this存起來吧,沒注意到他演算法有誤
12/26 16:41, 12F

12/26 16:44, , 13F
不然就轉成遞迴logn的演算法
12/26 16:44, 13F
不好意思 請問我的演算法哪裡錯了呢 我還是寫不出來QQ

12/26 18:44, , 14F
對耶,我沒注意忘記 add 是傳 HugeInt 了,sor
12/26 18:44, 14F
※ 編輯: steve1012 來自: 140.112.7.214 (12/28 16:12)
文章代碼(AID): #1EzpM8zi (C_and_CPP)
文章代碼(AID): #1EzpM8zi (C_and_CPP)