[英]Strange compile error when overloading operator !=
I have created my own version of operator !=
so that I can use p != NULL
instead of p->b == 0
. 我创建了自己的
operator !=
版本,以便可以使用p != NULL
代替p->b == 0
。 However, when compiling it (g++ v4.7.3 on Ubuntu 12.04), I get the error: 但是,在编译它时(在Ubuntu 12.04上为g ++ v4.7.3),出现错误:
$ g++ -std=c++11 te2b.cc
te2b.cc:8:41: error: ‘bool operator!=(strDum*, void*)’ must have an argument of class or enumerated type
Here is the code snippet: 这是代码片段:
#include <vector>
#include <iostream>
struct strDum {
int a;
int b;
};
bool operator!= (strDum *p, void *unused) {
return p->b != 0;
}
int main(void) {
strDum *x = (strDum*) malloc(sizeof(strDum) * 4);
x[0].a = 10; x[0].b = 20;
x[1].a = 100; x[1].b = 200;
x[2].a = 1000; x[2].b = 0;
strDum *y;
for (y=x; y!= NULL; y++) {
printf("%5d %5d\n", y->a, y->b);
}
return 0;
}
Any ideas? 有任何想法吗?
By the way, I prefer p != NULL
to p->b == 0
because the structure strDum and the criteria may change frequently ( p != NULL
may become p->c == 0
) 顺便说一句,我更喜欢
p != NULL
而不是p->b == 0
因为结构strDum和条件可能会频繁更改( p != NULL
可能会变成p->c == 0
)
UPDATE1 UPDATE1
As the declaration bool operator!= (strDum *p, void *unused)
shows, p is only going to be compared with "NULL". 如声明
bool operator!= (strDum *p, void *unused)
所示,p仅将与“ NULL”进行比较。
You can not declare an operator which only takes pointers as arguments. 您不能声明仅将指针作为参数的运算符。 From the standard:
从标准:
13.5.6 Overloaded operators [over.oper]
13.5.6重载的运算符[over.oper]
An operator function shall either be a non-static member function or be a non-member function that has at least one parameter whose type is a class, a reference to a class, an enumeration, or a reference to an enumeration.
运算符应为非静态成员函数或具有至少一个参数的非成员函数,该参数的类型为类,对类的引用,枚举或对枚举的引用。 It is not possible to change the precedence, grouping, or number of operands of operators.
不能更改运算符的优先级,分组或操作数的数量。 The meaning of the operators = , (unary) & , and , (comma), predefined for each type, can be changed for specific class and enumeration types by defining operator functions that implement these operators.
通过定义实现这些运算符的运算符功能,可以为特定的类和枚举类型更改为每种类型预定义的运算符=,(一元)和&和(逗号)的含义。 Operator functions are inherited in the same manner as other base class functions.
运算符函数的继承方式与其他基类函数相同。
You can't declare an operator overloaded function that takes pointers as arguments. 您不能声明将指针作为参数的运算符重载函数。
Consider doing this instead: 考虑改为这样做:
#include <iostream>
struct strDum {
int a;
int b;
};
template <typename T>
bool operator!= (strDum const& p, T const& number) {
return p.b != number;
}
//may want to include other operators like == as well
int main(void) {
strDum *test = new strDum;
if (*test != 0){
// data member did not equal zero ...
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.