Strange compile error when overloading operator !=

时间:2015-05-24 21:37:24

标签: c++

I have created my own version of operator != so that I can use p != NULL instead of p->b == 0. However, when compiling it (g++ v4.7.3 on Ubuntu 12.04), I get the error:

$ 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)

UPDATE1

As the declaration bool operator!= (strDum *p, void *unused) shows, p is only going to be compared with "NULL".

2 个答案:

答案 0 :(得分:4)

You can not declare an operator which only takes pointers as arguments. From the standard:

13.5.6 Overloaded operators [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.

答案 1 :(得分:0)

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