【问题标题】:C++ template operator overloading not workingC ++模板运算符重载不起作用
【发布时间】:2013-06-17 09:33:37
【问题描述】:

我有这个功能:

void plusQueue(){
    PrioQueue<int> *a = new PrioQueue<int>(2);
    PrioQueue<int> *b = new PrioQueue<int>(2);

    a->push(3);
    b->push(5);
    a->push(7);
    b->push(2); 

    cout << "a"<<endl;
    a->print();
    cout << "b"<<endl;
    b->print();
    cout<<"Samenvoegen\n";
    PrioQueue<int> *c = new PrioQueue<int>(4);
    c = a + b;
    c->print();
}

还有这一行:

c = a + b;

会带来一些问题。我收到这条消息:

main.cpp:71:13: error: invalid operands of types 'PrioQueue<int>*' and 'PrioQueue<int>*' to binary 'operator+'

这是我的模板类中的一个重载运算符:

PrioQueue operator +(PrioQueue a) {
    PrioQueue temp = *this;

    T *bottom = a.getBottom();
    T *top = a.getTop();

    for (T *element = bottom; element < top; element++) {
        temp.push(*element);
    }
    return temp;
}

我在这里做错了什么?

【问题讨论】:

  • 你能做这样的广告指针吗? a、b、c 是指向PrioQueue 的指针,而不是PrioQueuestry *c = *a + *b;

标签: c++ templates operators operator-overloading


【解决方案1】:

由于某种原因,您正在动态分配对象,因此 abc 是指针。不能添加指针。

如果你真的想保留指针,那么你需要尊重它们来访问对象:

*c = *a + *b;

并记住在使用完对象后删除它们;你的代码像漏水一样泄露。

更有可能,您希望对象是自动的:

PrioQueue<int> a(2);
PrioQueue<int> b(2);

// populate them

PrioQueue<int> c = a + b;

【讨论】:

    【解决方案2】:

    也许是因为你说你得到的是 PrioQueue 而不是指针。 试试*a + *b

    【讨论】:

      猜你喜欢
      • 2021-02-12
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多