gpt4 book ai didi

c++ - 重载运算符时出现奇怪的编译错误!=

转载 作者:行者123 更新时间:2023-11-27 22:58:14 25 4
gpt4 key购买 nike

我已经创建了我自己的 operator != 版本,这样我就可以使用 p != NULL 而不是 p->b == 0。但是,在编译它时(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

这是代码片段:

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

有什么想法吗?

顺便说一下,我更喜欢p != NULL 而不是p->b == 0 因为结构strDum 和标准可能经常变化(p != NULL 可能变成 p->c == 0)

更新1

正如声明 bool operator!= (strDum *p, void *unused) 所示,p 只会与“NULL”进行比较。

最佳答案

您不能声明只接受指针作为参数的运算符。来自标准:

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.

关于c++ - 重载运算符时出现奇怪的编译错误!=,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30428607/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com