gpt4 book ai didi

c++ - 在运算符中使用 `this`

转载 作者:行者123 更新时间:2023-11-30 00:38:35 24 4
gpt4 key购买 nike

我有这样的东西:

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

CLASS 只是一些类。binop的原型(prototype)是

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 是 const 限定的。我对运算符的左右手大小所做的操作要求两者都是可变的。

据我所知,我在函数调用中传递某个对象并将其转换为引用时似乎存在问题……这对我来说意义不大。有什么建议吗?

最佳答案

Visual Studio 在这里违反了标准。

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

关于c++ - 在运算符中使用 `this`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10360749/

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