如果我删除我的函数原型并将函数从底部移到顶部一切正常,函数可以接受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);
}
答案 0 :(得分:0)
这是函数的实现,如下所示:
tyler Addition(tyler num1, tyler num2)
{
return (num1 + num2);
}
请注意,这是不是模板函数,因此C ++将其视为实际接受类型为tyler
的参数而不是将tyler
视为占位符。
如果您想稍后定义模板功能,那很好!只需重复模板标题:
/* Prototype! */
template <typename tyler>
tyler Addition(tyler num1, tyler num2)
/* ... other code! ... */
/* Implementation! */
template <typename tyler>
tyler Addition(tyler num1, tyler num2)
{
return (num1 + num2);
}