[問題] A類別的函式內 呼叫 A類別函式 出錯

作者: hunandy14 (Charlott.HonG)   2016-06-01 15:25:39
不好意思我又卡關QQ
[程式越寫越長了我把她分開了](https://goo.gl/u8lMBP)
我想問的是 Hw10_fun.cpp 的 72~75 行
底下會詳細說明,盡可能不讓你們花太多時間看程式碼
使用GGC編譯錯誤是
In file included from Hw10_main.cpp:8:0:
Hw10_fun.cpp: In instantiation of 'frac<T1> frac<T1>::operator+(const
frac<T1>&) [with T1 = int]':
Hw10_main.cpp:19:11: required from here
Hw10_fun.cpp:74:4: error: passing 'const frac<int>' as 'this' argument
discards qualifiers [-fpermissive]
t2=p.impro();
^
Hw10_fun.cpp:115:10: note: in call to 'frac<T1> frac<T1>::impro() [with T1
= int]'
frac<T1> frac<T1>::impro(){
^
frac 類別有三個變數,比如說
frac<int> a(1,2,3);
意思是分數 (1又3分之2)
impro()是轉換函式 把[帶分數]轉成[真分數]
在main()裡面測試成功是正確的結果
類別內有自定義的運算子,用來處理那三個變數
我想在重載運算子內將類別轉成假分數型態在運算
這樣比較好處理,這個函式也直接公開自由使用
// 運算子重載
template <typename T1>
frac<T1> frac<T1>::operator+(const frac &p){
frac<T1> temp;
frac<T1> t1,t2;
// t1=this->impro();
// t1.pri();
// t2=p.impro();
// t2.pri();
temp.num = this->num * p.den+
this->den * p.num;
temp.den = this->den * p.den;
// temp.mix = this->mix;
temp.flag = this->flag;
return temp;
}
template <typename T1> // 假分數
frac<T1> frac<T1>::impro(){
frac<T1> temp;
temp.mix = 0;
temp.num = this->mix*this->den + this->num;
temp.den = this->den;
temp.flag = this->flag;
return temp;
}
想請問了怎麼會出現這樣的錯誤,哪裡錯了QQ
this使用方式是->而不是點
不知道是不是這樣用
我這樣打可以編譯,可是出來的數值沒變
**解答:把呼叫的函數加上 const 修飾
記得定義(.h)也要改
作者: shadow0326 (非議)   2016-06-01 15:32:00
74行的p是const ref,impro不是const funcfrac<T1> frac<T1>::impro() const {...}
作者: EdisonX (卡卡獸)   2016-06-01 22:55:00
等下.. 你是把這個 template class , 拆成兩個檔案嗎 ?.h 用宣告,.cpp 用實作,是這樣嗎?
作者: tsoahans (ㄎㄎ)   2016-06-01 23:12:00
.h檔也要加const
作者: EdisonX (卡卡獸)   2016-06-02 00:01:00
耶... 我的疑問其實是 , 現在的 compiler 可以支援template 可以拆檔實現了?
作者: bibo9901 (function(){})()   2016-06-02 11:04:00
定義用 const 時宣告也要用 const
作者: Caesar08 (Caesar)   2016-06-02 14:58:00
template一直都可以拆檔 我從vs 2010開始用就是這樣了不會怎麼樣,但是為何不把Hw10_fun.cpp與Hw10_fun.h合併就算你真的要分開,那Hw10_main.cpp應該要先看到classfrac的declaration,而不是先看到frac的definition你這樣寫,很奇怪而已(然後很容易讓別人誤會)我說錯了,我另外回你一篇文章比較快

Links booklink

Contact Us: admin [ a t ] ucptt.com