有一些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;
答案 0 :(得分:2)
T
中有一个 const 对push()
的引用,但您的operator==
只接受非const引用。
bool wComplex::operator==(wComplex &El)
应该是
bool wComplex::operator==(wComplex const &El) const
或者,最佳地,您的operator==
应该是免费功能:
bool operator==(wComplex const & Left, wComplex const & Right) {
}
如果您不希望外部访问wComplex的成员变量,则需要使操作符成为友元函数:
class wComplex {
...
friend bool operator==(wComplex const & Left, wComplex const & Right);
...
};
编辑:关于更新的问题:
您无法分配到this
。 this
的类型为T * const
- 因为修改它是没有意义的。您要做的是更改指向当前类的外部变量,除非将此外部变量作为参数传入,否则不能从类成员函数内部执行此操作。
我认为您需要创建一个管理“节点”类实例的“队列”类 - 尝试组合容器和包含的元素并不是一个好主意
此外,继承标准库容器很少是个好主意。如果您想使用std::queue
,请创建成员变量。
答案 1 :(得分:1)
变化:
bool wComplex::operator==(wComplex &El){
成:
bool wComplex::operator==(const wComplex &El) const {
答案 2 :(得分:0)
未来的一个提示:
const关键字,无论是放在哪里,也可以放在任何地方。
显然,无论你身在何方都可以做得更好。