簡體   English   中英

為什么此模板功能原型無法正常工作?

[英]Why doesn't this template function prototype work properly?

如果刪除函數原型並將函數從底部移到頂部,則一切正常,並且該函數可以接受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);
}

這是該函數的編寫過程:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM