gpt4 book ai didi

C++ 类模板

转载 作者:行者123 更新时间:2023-11-28 01:28:50 25 4
gpt4 key购买 nike

我正试图让这些 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|error: no match for 'operator<<' (operand types are 'std::basic_ostream::__ostream_type {aka std::basic_ostream}' and 'mcomplex')

|62|note: candidate: std::ostream& operator<<(std::ostream&, mcomplex&)

|77|error: invalid initialization of non-const reference of type 'mcomplex&' from an rvalue of type 'mcomplex'

|78|error: no match for 'operator<<' (operand types are 'std::basic_ostream::__ostream_type {aka std::basic_ostream}' and 'mcomplex')

谁能告诉我这里的错误是什么?

最佳答案

您的 pop() 函数正在返回一个临时值。对该值进行非常量引用没有意义。

关于C++ 类模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52572611/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com