gpt4 book ai didi

c++ - 为什么这个模板函数原型(prototype)不能正常工作?

转载 作者:太空宇宙 更新时间:2023-11-04 12:56:01 25 4
gpt4 key购买 nike

如果我删除我的函数原型(prototype)并将函数从底部移到顶部,一切正常,并且该函数可以接受 float 或 int 作为数据类型。您通常不应该对函数进行原型(prototype)设计吗?另外,我有点好奇为什么这个函数只有在顶部才有效。我很确定这是一个范围界定问题,但出于某种原因它让我难以理解。

#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);
}

最佳答案

下面是函数的实现:

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);
}

关于c++ - 为什么这个模板函数原型(prototype)不能正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46637652/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com