【问题标题】:Why doesn't this template function prototype work properly?为什么这个模板函数原型不能正常工作?
【发布时间】:2017-10-09 01:19:59
【问题描述】:

如果我删除我的函数原型并将函数从底部移动到顶部,一切正常,并且该函数可以接受 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++ function templates


    【解决方案1】:

    下面是函数的实现:

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

    【讨论】:

    • 我在关注newboston的模板函数教程,只是他没有原型。我通常对我的函数进行原型设计,所以我试图找到一种方法来做到这一点。除此之外,我的代码与他的完全相同。除此之外,我可以假设您给我的第二个代码框是模板函数的正确示例吗?
    • 老实说,我见过的任何 C++ 视频教程都没有正确地教授基础和高级部分,newboston 肯定包括在内。我建议买一本关于 C++ 的书。
    • 我刚刚更新了我的答案,以更清楚地表明您可以保留您的原型稍后定义模板函数。您只需要在这两种情况下都包含模板标题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-30
    • 2023-02-20
    相关资源
    最近更新 更多