有一些類wComplex與==
運算符。問題與== ==運算符
#ifndef WCOMPLEX_H
#define WCOMPLEX_H
#include <stdio.h>
// sample class of complex-like numbers with weird `==` operator
class wComplex{
private:
double realPart;
double imagePart;
public:
wComplex();
wComplex(double R);
wComplex(double R, double I);
bool operator==(wComplex &);
void print();
};
wComplex::wComplex(){
realPart = 0;
imagePart = 0;
}
wComplex::wComplex(double R){
realPart = R;
imagePart = 0;
}
wComplex::wComplex(double R, double I)
{
realPart = R;
imagePart = I;
}
bool wComplex::operator==(wComplex &El){
double diff = realPart*realPart + imagePart*imagePart -
El.realPart*El.realPart - El.imagePart*El.imagePart;
return (diff == 0);
}
void wComplex::print(){
printf("(%g) + (%g)i\n", realPart, imagePart);
}
#endif
它成功地與東西的工作就像是:
wComplex A(1, 2);
wComplex B(2, 4);
wComplex C(2, 1);
(A == C)是真實的。
還有另一個類 - 隊列狀。但它應該控制其他元素的平等(含義爲==
)的新推動元素。
#ifndef MYQueue_H
#define MYQueue_H
#include <stdio.h>
#include <queue>
template<typename T>
class myQueue : public std::queue<T>{
public:
myQueue(){
printf("new myQueue successfully created\n");
}
void push (const T& x){
myQueue* tmp = new myQueue;
myQueue* old = new myQueue;
old = this;
bool MATCH = false;
while(!old->empty()){
T el = old->front();
if(el == x){
MATCH = true;
tmp->push(x);
}
else
tmp->push(el);
old->pop();
}
if(!MATCH)
tmp->push(x);
this = *tmp;
delete tmp;
delete old;
}
};
#endif
所以,現在有一個問題
myqueue.h: In member function ‘void myQueue<T>::push(const T&) [with T = wComplex]’:
shit.cpp:23: instantiated from here
myqueue.h:26: error: no match for ‘operator==’ in ‘el == x’
wcomplex.h:36: note: candidates are: bool wComplex::operator==(wComplex&)
myqueue.h:36: error: lvalue required as left operand of assignment
make: *** [compile] Error 1
其實,我不明白爲什麼no match for ‘operator==’ in ‘el == x’
,我應該怎麼辦?任何想法
UPD:以及如何替換this
元素tmp
? 這是一個與this = *tmp;
我假設el的意思是一個迭代器,你在上面的聲明中有一個錯字。如果是這樣,那麼使用'(* el)== x' ...你的迭代器沒有那個操作符定義了底層對象,如果它是與T相同的類型。如果去引用你的迭代器不起作用您的隊列聲明最有可能存在另一個問題。 – AJG85 2011-03-16 23:07:07
只是一個側面說明 - 比較兩個複數應該很容易做到:'return realPart == El.realPart && imagePart == El.imagePart;'否則1將等於我,如果我沒有錯過任何東西。 – Mario 2011-03-16 23:09:24
@Mario這只是一個很奇怪的樣本,不是正確的 – 2011-03-16 23:11:20