在运算符中使用“this”

Use of `this` in operators

本文关键字:this 运算符      更新时间:2023-10-16

我有这样的东西:

CLASS CLASS::operator|(CLASS& right) {
    return binop(*((CLASS*) this), right, OP_OR);
}

只是一些类。Binop的原型是

CLASS binop(CLASS& left, CLASS& right, OP op);

这一切都工作正常,并使用Visual C++ 2010进行编译,但在g ++中失败并显示错误:

someheader.h: In member function 'void CLASS::set(int64_t)':
someheader.h:469:29: error: no match for 'operator|' in '*(CLASS*)this | CLASS(bit)'
someheader.h:469:29: note: candidate is:
someheader.h:376:1: note: CLASS CLASS::operator|(CLASS&)
someheader.h:376:1: note:   no known conversion for argument 1 from 'CLASS' to 'CLASS&'

现在,我在将当前对象 (*this) 作为某个参数传递时遇到了问题,所以我显式抛弃它以删除指针上的 const 限定符,它工作正常,似乎欺骗 Visual C++ 编译器接受它作为普通指针。 G++似乎不喜欢这样。如果我移除铸件,它仍然会给我一个错误,因为this是符合标准的。我对运算符的左手和右手大小所做的工作要求两者都是可变的。

从我所能收集的信息来看,我传递一些对象并将其转换为函数调用中的引用似乎存在问题......这对我来说没有多大意义。有什么建议吗?

Visual Studio在这里违反了标准。

您的右手参数是临时的,根据C++规则,临时参数不能与非常量引用匹配。

你调用operator|这样的东西:

int bit = 0x02;
CLASS result = *this | (CLASS)bit;

您的操作员会参考。

CLASS CLASS::operator| (CLASS &right);

为了解决 GCC 的问题,我发现要么这样称呼它:

CLASS result = *this | (CLASS &)bit;

或者像这样定义运算符:

CLASS CLASS::operator| (CLASS &&right); //C++11

两者都导致它返回正确的结果。不过我不能保证其中一个是解决方案。