編輯之前您閱讀:對不起。我沒有添加換行符,所以它似乎混亂,我不能刪除這個問題,因爲我還沒有註冊,遺憾浪費你的時間人。簡單的簡單模板返回奇數?
我剛剛第一次使用了模板(用於查找兩個數字的MIN)而不是宏,我喜歡它!但是,當我試圖修改,讓我自己的模板就徹底失敗了。這裏是我的代碼:
#include <stdio.h>
template <class T> T min(T a, T b) {
return a < b ? a : b;
};
//My attempt now.. because add could be int, float, etc; I wanted a template.
template <class T> T add(T a, T b) {
return a + b;
};
int main(){
printf("%f\n", min(1.3, 2.2)); //(Does not appear in console?)
printf("%d", add(1, 10)); //1.300000 (how is an int show as float? lol)
printf("%f", add(5.1, 7.34)); //1112.440000
return 0;
}
現在奇怪的結果是在評論..閩工作正常,但是當我改變它從比較「a + b」它阻止了min的工作,並傳遞給我奇怪的浮點值?!
我用錯了嗎? ,它應該是別的嗎?那是什麼意思?我瞭解基礎知識,所以簡單的說明就可以了。謝謝!
不要難過,只要接受正確的答案。 – 2010-06-29 10:47:36