繁体   English   中英

C ++模板运算符重载不起作用

[英]C++ template operator overloading not working

我有这个功能:

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

我在这里做错了什么?

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

如果您确实要保留指针,则需要引用它们来访问对象:

*c = *a + *b;

并记得在完成处理后删除对象; 您的代码泄漏就像泄漏的东西。

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

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

// populate them

PrioQueue<int> c = a + b;

可能是因为您说得到的是PrioQueue,而不是指针。 尝试*a + *b

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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