我遇到一个问题,我有一个名为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'))”
我已经搜索了一段时间,没有任何东西可以指出这个问题。我该如何解决?
答案 0 :(得分:1)
您已将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];
}
答案 1 :(得分:0)
事实证明,我一如既往地害怕寻找东西。 tileread[ aux_int_1, aux_int 2 ]
应该是tileread( aux_int_1, aux_int 2 )
。
如果是蛇,它会咬我几次。谢谢@NathanOliver!