我遇到以下问题: 我需要使用枚举来枚举4个继承的类(此时它们与枚举之间没有区别)然后通过名为“whoAmI”的虚函数返回类型,我不明白我的语法如何会做返回部分 以下是相关代码;
virtual void whoAmI();
enum gettype { easyTile, cropTile, waterTile, mediumTile};
in class.cpp
void tile::whoAmI()
{
}
答案 0 :(得分:2)
您可以将函数的返回类型更改为enum
的名称,然后使用= 0
声明基类是纯虚拟的。
class ITile
{
public:
enum class EType { easy, crop, water, medium };
virtual EType whoAmI() const = 0;
};
然后派生类可以override
此方法返回正确的enum
类型,例如
class EasyTile : public ITile
{
public:
EasyTile() = default;
EType whoAmI() const override { return EType::easy; }
};
class CropTile : public ITile
{
public:
CropTile() = default;
EType whoAmI() const override { return EType::crop; }
};
以示例(live demo)
为例int main()
{
std::vector<std::unique_ptr<ITile>> tiles;
tiles.emplace_back(new EasyTile);
tiles.emplace_back(new CropTile);
for (auto const& tile : tiles)
{
std::cout << static_cast<int>(tile->whoAmI()) << std::endl;
}
}
将输出
0
1
答案 1 :(得分:1)
您可以轻松地执行此操作:
class TileBase
{
public:
enum Type { easyTile, cropTile, waterTile, mediumTile };
virtual Type whoAmI() const = 0;
virtual ~TileBase() = default;
};
class EasyTile : public TileBase
{
Type whoAmI() const override { return easyTile; }
};
您看,您需要将enum Type
指定为返回类型而不是void
。
答案 2 :(得分:0)
#include <iostream>
using namespace std;
class Tile{
public:
enum getType { easyTile, cropTile, waterTile, mediumTile};
virtual getType whoAmI(){}
};
class easyTile:public Tile{
public:
getType whoAmI(){return getType::easyTile;}
};
class cropTile: public Tile{
public:
virtual getType whoAmI(){return getType::cropTile;}
};
class waterTile: public Tile{
public:
virtual getType whoAmI(){return getType::waterTile;}
};
class mediumTile: public Tile{
public:
virtual getType whoAmI(){ return getType::mediumTile;}
};
int main() {
Tile *T = new cropTile;
cout << T->whoAmI() << endl;
delete T;
return 0;
}
输出:1