C++ 为什么模板类不能为double正常工作?
我有以下代码:C++ 为什么模板类不能为double正常工作?,c++,templates,template-classes,C++,Templates,Template Classes,我有以下代码: #include<cstdio> #include<iostream> #include<cmath> using namespace std; template <class T> class Stack { private: T a[1001]; int i=0,j; public: void pop(void) { a[i-1]=0.0; a[i-1]='\0';
#include<cstdio>
#include<iostream>
#include<cmath>
using namespace std;
template <class T> class Stack
{
private:
T a[1001];
int i=0,j;
public:
void pop(void)
{
a[i-1]=0.0;
a[i-1]='\0';
}
void push(T &x)
{
a[i++]=x;
}
void push(const char &x)
{
a[i++]=x;
}
void top(void)
{
cout<<a[i-1];
}
};
int main()
{
Stack<char>s1;
s1.push('a');
s1.push('b');
s1.top();
s1.pop();
cout<<"\n";
Stack<int>s2;
s2.push(10);
s2.push(20);
s2.top();
s2.pop();
cout<<"\n";
Stack<double>s3;
s3.push(5.50);
s3.push(7.50);
s3.top();
s3.pop();
cout<<"\n";
return 0;
}
为什么双打显示7而不是7.5?
当我显式地专门化double而不使用引用操作符时,它工作得很好
void push(double x)
{
a[i++]=x;
}
这为double提供了正确的输出。
但是,当我这样做的时候,它给出了错误
void push(T x)
{
a[i++]=x;
}
void push(const char &x)
{
a[i++]=x;
}
如何解决这个问题?
如何为double显示正确的输出?使用时
s3.push(7.50);
它解决了过载问题
void push(const char &x)
{
a[i++]=x;
}
由于7.5无法转换为双精度&,因此需要使用:
void push(T &x)
{
a[i++]=x;
}
结果,在堆栈中得到截断的值7
如果希望调用解析tovoid pushT&x,请创建一个变量并在调用中使用该变量
double x = 7.5;
s3.push(x);
我想补充R Sahu的答案。在C++11中,引入了一种称为r值引用的新型引用。R值引用用于引用未命名变量,在本例中,这就是7.5 R Sahu所说的7.5不能转换为double&是指l值引用(即您的double&)不能绑定到R值(即您的7.5) L值引用T&只能绑定到L值。R值引用T&&只能绑定到R值。只读l值引用const T&但是,可以绑定到l值或r值,只读或非只读。因此,函数重载解析将解析为pushconst char&x,因为它接受只读l值引用
感谢阅读。左值引用无法绑定到右值。此外,您没有专门化任何.OT,但您的pop函数实际上没有递减i@MattMcNabb我知道,它不会减少我。我只是用它来显示输出。@KhairulBasar当参数类型为const&时,输入值在临时内存位置被截断,临时内存位置被传递给函数。另一个可能的修复方法是按值或按常量引用推取x谢谢。但如果我只是简单地使用voidpushchar&x,它对所有人都很有效……这可以吗,还是会产生bug?
double x = 7.5;
s3.push(x);