c++模板操作符重载不起作用



我有这个函数:

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<<"Samenvoegenn";
    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, bc是指针。你不能添加指针。

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

*c = *a + *b;

并记住在使用完对象后删除它们;你的代码就像一个有漏洞的东西。

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

PrioQueue<int> a(2);
PrioQueue<int> b(2);
// populate them
PrioQueue<int> c = a + b;

可能因为你说你得到一个PrioQueue而不是一个指针。try *a + *b

最新更新