【问题标题】:C++ class templateC++ 类模板
【发布时间】:2018-09-29 21:16:30
【问题描述】:

我正在尝试让这些 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

|62|注意:候选:std::ostream& 运算符

|77|错误:类型的非常量引用的无效初始化 来自“mcomplex”类型的右值的“mcomplex&”

|78|error: no match for 'operator

谁能说明这里的错误是什么?

【问题讨论】:

  • 您不能将临时值传递给将非常量引用作为参数的函数。您的重载必须将 const 引用作为参数。
  • 你试过写非模板版本吗?

标签: c++ templates


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    虽然这取决于你的目的,但你应该抛出如下异常,而不是 T():

    if (top==-1)
    {
        throw std::runtime_error("stack is empty");
    }
    

    Demo

    【讨论】:

    • 是的,这样好多了。我目前正在学习 c++,不知道异常。
    【解决方案3】:

    让这件事终于奏效了。 更正了。

    ostream& operator<< (ostream &o,const mcomplex &c)
    {
        o << c.real << "\t" << c.img;
        return o;
    }
    

    if (top==-1)
        {
            cout << endl << "stack is empty" << endl;
            return T();
        }
    

    【讨论】:

      猜你喜欢
      • 2011-07-14
      • 1970-01-01
      • 2010-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      相关资源
      最近更新 更多