[英]C++ class template
i am trying to get these class template in C++ to work. 我试图使这些类模板在C ++中工作。 But there is always this error. 但是总会有这个错误。 there is some kind of error in overloading but i don't know what. 重载中存在某种错误,但我不知道是什么。 i have tried overloading << operator using member function but there is still error. 我尝试使用成员函数重载<<运算符,但仍然存在错误。
#include <iostream>
using namespace std;
const int MAX = 10;
template <class T>
class mstack
{
T stk[MAX];
int top;
public:
mstack()
{
top = -1;
}
void push(T data)
{
if(top==MAX-1)
{
cout << endl << "stack is full" << endl;
}
else
{
top++;
stk[top] = data;
}
}
T pop()
{
if (top==-1)
{
cout << endl << "stack is empty" << endl;
return NULL;
}
else
{
T data = stk[top];
top--;
return data;
}
}
};
class mcomplex
{
float img, real;
public:
mcomplex()
{
real = 0;
img = 0;
}
mcomplex(float r, float i)
{
real = r;
img = i;
}
friend ostream& operator<< (ostream &o,mcomplex &c);
};
ostream& operator<< (ostream &o, mcomplex &c)
{
o << c.real << "\t" << c.img;
return o;
}
int main()
{
mcomplex c1(1.5f,2.5f), c2(3.5f,4.5f), c3(-1.5f,-0.6f);
mstack <mcomplex> s3;
s3.push(c1);
s3.push(c2);
s3.push(c3);
cout << endl << (s3.pop());
cout << endl << s3.pop();
cout << endl << s3.pop() << endl;
return 0;
}
compiler error is as following: 编译器错误如下:
|76|error: no match for 'operator<<' (operand types are 'std::basic_ostream::__ostream_type {aka std::basic_ostream}' and 'mcomplex') | 76 |错误:与'operator <<'不匹配(操作数类型为'std :: basic_ostream :: __ ostream_type {aka std :: basic_ostream}'和'mcomplex')
|62|note: candidate: std::ostream& operator<<(std::ostream&, mcomplex&) | 62 |注:候选项:std :: ostream&运算符<<(std :: ostream&,mcomplex&)
|77|error: invalid initialization of non-const reference of type 'mcomplex&' from an rvalue of type 'mcomplex' | 77 |错误:从类型'mcomplex'的右值对类型'mcomplex&'的非常量引用进行了无效的初始化
|78|error: no match for 'operator<<' (operand types are 'std::basic_ostream::__ostream_type {aka std::basic_ostream}' and 'mcomplex') | 78 |错误:与'operator <<'不匹配(操作数类型为'std :: basic_ostream :: __ ostream_type {aka std :: basic_ostream}'和'mcomplex')
can anyone show what is the error here? 谁能显示这里的错误是什么?
Your pop() function is returning a temporary value. 您的pop()函数正在返回一个临时值。 Taking non-const reference to this value doesn't make sense. 对该值采用非常量引用是没有意义的。
Got this thing to finally work. 得到了这个东西终于可以工作了。 corrections were. 更正了。
ostream& operator<< (ostream &o,const mcomplex &c)
{
o << c.real << "\t" << c.img;
return o;
}
and 和
if (top==-1)
{
cout << endl << "stack is empty" << endl;
return T();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.