无法将返回的枚举与枚举进行比较

Cannot compare returned enum to enum

本文关键字:枚举 比较 返回      更新时间:2023-10-16

我遇到了一个问题,我有一个叫做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!