无法将返回的枚举与枚举进行比较
Cannot compare returned enum to enum
我遇到了一个问题,我有一个叫做tile
的枚举,一个名为tileread
的函数返回一个tile
值和一个if
语句,该语句将返回的值与静态值进行比较,也是tile
:
enum tile{ tile_void, tile_flat };
tile tileread( const int x, const int y ) {
if( x < 0 || x >= level_length || y < 0 || y >= level_width ) {
return tile_void;
}
return level_tile[x][y];
}
if( tileread[ aux_int_1 ][ aux_int_2 ] == tile_void ) {
player_vel[2] -= player_grav;
}
但是,编译器会抛出一个错误,指出"'operator='不匹配(操作数类型是'tile(int, int('和'tile'(">
我已经搜索了一段时间,没有任何迹象表明这个问题。我该如何解决这个问题?
您已将tileread
定义为函数。 和
tileread[ aux_int_1 ][ aux_int_2 ]
(通常(是用于访问数组数组(或指针数组或指向指针的指针(中的元素的语法,而不是用于调用函数的语法。 相反,您需要:
if ( tileread( aux_int_1, aux_int_2 ) == tile_void ) {
然后它应该起作用。
现在,如果您真的想使用方括号,就好像tileread
数组一样,您可以使用运算符重载进行设置。 运算符重载的第一步是考虑是否真的应该使用运算符重载。 特殊语法对您尝试解决的问题有多大意义? 它对使用你的界面的程序员更有用,还是对遇到它的程序员更困惑? (即使你从未打算共享你的代码,那个程序员也可以在你把项目放在一边,然后在几个月或几年后回到它之后。
如果您认为这是值得的,那么定义名称tileread
允许tileread[ aux_int_1 ][ aux_int_2 ]
可能如下所示:
class TileReadType {
public:
constexpr TileReadType() noexcept = default;
private:
class RowProxy {
public:
tile operator[] ( int y ) const;
private:
constexpr explicit RowProxy( int x ) noexcept : x(x) {}
int x;
friend TileReadType;
};
public:
constexpr RowProxy operator[] ( int x ) const noexcept
{ return RowProxy(x); }
};
constexpr TileReadType tileread{};
// Either mark "inline", or put in a source file:
tile TileReadType::RowProxy::operator[] ( int y ) const
{
// Code that was in the function goes here:
if( x < 0 || x >= level_length || y < 0 || y >= level_width ) {
return tile_void;
}
return level_tile[x][y];
}
事实证明,我和往常一样,在寻找东西方面很糟糕。tileread[ aux_int_1, aux_int 2 ]
应该是tileread( aux_int_1, aux_int 2 )
.
如果是蛇,它会咬我好几次。谢谢,@NathanOliver!
相关文章:
- 不带大括号的枚举形式
- 枚举环境变量的惯用C++14/C++17方法
- 类似枚举的计算常量
- 如何正确实现和访问运算符的各种自定义枚举器
- 错误:从"int"到枚举c++的转换无效
- C++中构造函数中的枚举
- 标准::可选枚举的比较运算符
- 将用户值与枚举中的值进行比较
- 无法将返回的枚举与枚举进行比较
- 比较枚举的值会给出编译器错误
- C ++枚举可以与整数进行比较,但不能从整数分配?
- 比较枚举类值时的奇怪行为
- 为什么我没有警告枚举比较不匹配
- 将错误代码枚举与 std::error_code 进行比较
- 重新定义枚举的比较运算符
- 我是否正确地将枚举值与C++的"or"运算符进行比较?
- gtest枚举和对象之间的比较
- 将枚举与整数进行比较
- 比较枚举类型时出现逻辑错误
- 为什么我不能分配错误的枚举元素,但可以与错误的枚举元素进行比较?