在运算符中使用“this”
Use of `this` in operators
我有这样的东西:
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
两者都导致它返回正确的结果。不过,我不能保证其中一个是解决方案。
相关文章:
- 运算符++();调用和++(*this)有什么区别?
- 为什么在通过引用返回运算符分配时取消引用'this'指针?
- 如何在"this"上调用运算符()?
- 从 std::ostream 重载 << 运算符时,为什么编译器会给出"too many parameters for this operator function"错误?
- 当取消引用运算符 (*) 重载时,*this 的使用是否受到影响?
- C++指针上的关键字运算符"this"
- 假设我有作业运算符,我的复制构造函数是this = obj可以
- 为什么我的重载运算符+在向自身添加变量时会在返回时使"this"未初始化?
- "return *this"赋值运算符重载
- 是否可以在实例方法中使用带有"this"的重载运算符?
- 重载 = 运算符时如何使用 THIS 指针
- 运算符+=可以调用自己,但"*this"与"rhs"交换吗?
- 可能的分段错误:是否正确使用了"this->"运算符?
- 使用 This 关键字和运算符重载
- 在运算符中使用“this”
- 由 sf::P acket 定义的运算符<<是否与 sf::P acket 派生类的 (*this) 一起工作?
- 运算符this的c++重载
- c++重写运算符和this
- 我可以在运算符=中使用placement new(this)吗
- 重载类函数中的按位和 (&) 运算符和"*this"