1
如果我刪除我的函數原型並將函數從底部移動到頂部,一切正常,函數可以接受float或int作爲數據類型。你通常不應該原型功能?另外,我對這個函數爲什麼只有在頂端時才起作用有點好奇。我很確定這是一個範圍問題,但由於某種原因它正在超出我的頭。爲什麼這個模板函數原型不能正常工作?
#include <iostream>
#include <math.h>
#include <iomanip>
using namespace std;
template <class tyler> // function template
tyler Addition(tyler, tyler); // function prototype
int main()
{
setprecision(2); //limits decimal output to 2 places
int num1, num2;
float num3, num4;
cout << "Enter your first number: \n";
cin >> num1;
cout << "Enter your second number: \n";
cin >> num2;
cout << num1 << " + " << num2 << " = " << Addition(num1, num2);
cout << "Enter your third number: (round 2 decimal places, e.x. 7.65) \n";
cin >> num3;
cout << "Enter your fourth number: (round 2 decimal places, e.x. 7.65 \n";
cin >> num4;
cout << num3 << " + " << num4 << " = " << Addition(num3, num4);
cin.clear(); // Clears the buffer
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // Ignores anything left in buffer
cin.get(); // Asks for an input to stop the CLI from closing.
return 0;
}
tyler Addition(tyler num1, tyler num2)
{
return (num1 + num2);
}
我正在關注新波士頓的模板函數教程,並且只有他沒有將其原型化。通常我的功能是原型,所以我試圖找到一種方法來做到這一點。除此之外,我的代碼和他完全一樣。 除此之外,我可以假設你給我的第二個代碼是一個模板函數的適當例子嗎? –
我會誠實地說,我沒有看到正確的C++視頻教程,教導了基礎知識和高級部分,新的波士頓絕對包括在內。我建議拿起一本關於C++的書。 – user975989
我剛剛更新了我的答案,更清楚地表明您可以保留原型*和*以後定義模板函數。在這兩種情況下,您只需要包含模板標頭。 – templatetypedef