我在 C 中學習主題模板,它說我也可以在模板語法中分配資料型別。但是,如果我在類的物件中傳遞不同的資料型別并呼叫我的類的方法,它應該拋出錯誤或垃圾輸出,但它不會,而如果我在宣告物件時分配資料型別,它會給出正確的輸出類并呼叫它。為什么會這樣?
這是我正在練習的程式
#include <iostream>
using namespace std;
template <class t1 = int, class t2 = int>
class Abhi
{
public:
t1 a;
t2 b;
Abhi(t1 x, t2 y)
{
a = x;
b = y;**your text**
}
void display()
{
cout << "the value of a is " << a << endl;
cout << "the value of b is " << b << endl;
}
};
int main()
{
Abhi A(5,'a');
A.display();
Abhi <float,int>N(5.3,8.88);
N.display();
return 0;
}
我在第一個物件A中遇到問題,而第二個物件N給出了正確的輸出
上述程式對第一個物件的輸出是
the value of a is 5
the value of b is a
上述程式對第二個物件的輸出是
the value of a is 5.3
the value of b is 8
uj5u.com熱心網友回復:
Achar可以隱式轉換為int. 雖然 的型別A會被 C 20 推匯出為Abhi<int,char>. 這就是為什么當你輸出它時你得到一個a而不是它對應的整數表示。
有關該機制的更詳細說明,請參閱CTAD。
更有趣的是為什么你的編譯器會隱式轉換double為. 這表明您的編譯器警告標志不夠高,或者您正在主動忽略它們。intfloatN
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/519906.html
標籤:C 模板
上一篇:分頁firebase實時資料庫
