2013-06-20 86 views
0

我有這樣的功能: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<<"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; 
} 

我幹了什麼錯在這裏做什麼?

+0

你能指出那樣的指針嗎? a,b,c是指向「PrioQueue」**而不是「PrioQueues」的指針。 'try * c = * a + * b;' – andre

回答

3

出於某種原因,您正在動態分配對象,因此a,bc是指針。你不能添加指針。

如果你真的想保持指針,那麼你需要尊重他們訪問的對象:

*c = *a + *b; 

,記得刪除的對象,一旦你與他們進行;你的代碼泄漏就像漏洞一樣。

更有可能的是,你要的對象是自動的:

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

// populate them 

PrioQueue<int> c = a + b; 
+0

謝謝,就是這樣! :) –

1

也許是因爲你說你得到一個PrioQueue,而不是一個指針。 嘗試*a + *b