Reputation: 397
i am trying to get these class template in C++ to work. 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')
|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')
can anyone show what is the error here?
Upvotes: 0
Views: 146
Reputation: 2880
Although it depends on your purpose, you should throw something exception like as follows, not T():
if (top==-1)
{
throw std::runtime_error("stack is empty");
}
Upvotes: 1
Reputation: 397
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();
}
Upvotes: 0
Reputation: 51
Your pop() function is returning a temporary value. Taking non-const reference to this value doesn't make sense.
Upvotes: 1