c++ - C++ 类模板
问题描述
我试图让这些 C++ 中的类模板工作。但是总是有这个错误。重载时出现某种错误,但我不知道是什么。我尝试使用成员函数重载 << 运算符,但仍然存在错误。
#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;
}
编译器错误如下:
|76|错误:'operator<<' 不匹配(操作数类型是 'std::basic_ostream::__ostream_type {aka std::basic_ostream}' 和 'mcomplex')
|62|注:候选:std::ostream& 运算符<<(std::ostream&, mcomplex&)
|77|错误:从“mcomplex”类型的右值初始化“mcomplex&”类型的非常量引用无效
|78|错误:'operator<<' 不匹配(操作数类型为 'std::basic_ostream::__ostream_type {aka std::basic_ostream}' 和 'mcomplex')
谁能显示这里的错误是什么?
解决方案
您的 pop() 函数正在返回一个临时值。对该值进行非常量引用是没有意义的。
推荐阅读
- python - python venv 可以与 plpython3u 一起用于 postgresql 吗?
- java - Spark 流式传输:由于 java.lang.NullPointerException,运行作业流式传输作业时出错
- javascript - js如何将其(10000000000000000000000000000)长度计算为5?
- ios - Safari 或 IOS 中视频的 aws-sdk getSignedUrl 不起作用
- windows - Windows 命令在 cmd 但不是 .bat 文件中工作
- kubernetes - Traefik + Keycloak Gatekeeper Websocket 认证
- c# - 如何在不接触磁盘的情况下将 assembly.load(byte[]) 托管的 dll 加载到内存中
- c++ - 有没有办法制定一个也可以检测高原的峰值发现函数?
- python - Python np.select 将某些条件匹配到多项选择
- c# - 编写自己的 json 属性的最佳实践,该属性将被 json.net 反序列化忽略