简体   繁体   中英

C++ class template

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?

Your pop() function is returning a temporary value. Taking non-const reference to this value doesn't make sense.

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");
}

Demo

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();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM