草庐IT

c++ - 是否可以拥有来自同一基类的不同对象的数组?

coder 2024-02-09 原文

我正在尝试为游戏设计武器类别。这是我为满足我的需要而编写的一些代码:

class weapon {

 public:
  int fireRate;
  int bulletDamage;
  int range;
  ofImage sprite;
  ofImage bulletSprite;
  bullet bullets[50];
  int activeBullet;

 public:
  void fire();
};

class machineGun: public weapon {
 public: 
  void fire();
};

class flamer: public weapon {
 public: 
  void fire();
};

然后我想像这样定义一个武器数组:

//Weapon variables
const int totalWeapons = 2;
int currentWeapon = 1;
weapon weapons[totalWeapons];

我希望元素 [0] 代表 machineGun 类,元素 [1] 代表火焰喷射器类。我是否以正确的方式解决这个问题?我应该以某种方式重构它吗?我如何获得容纳这两种不同武器的阵列?

我的想法是这样的,当我调用 weapons[0].fire(); 我得到一个 machineGun 类,当我调用 weapons[1].fire(); 我得到了火焰喷射器。




编辑:感谢您的帮助。我在使用“weapons[0] = new machineGun;”时遇到了一些问题。当我尝试运行此代码时出现错误“无法分配常量大小为 0 的数组”。

有没有人知道为什么这不起作用?我更新后的代码看起来像这样:

//Weapon variables
const int totalWeapons = 2;
int currentWeapon = 1;
weapon weapons[totalWeapons];
weapons[0] = new machineGun;
weapons[1] = new flamer;

但是我得到了很多错误:

1>gameplay.cpp(49) : error C2466: cannot allocate an array of constant size 0
1>gameplay.cpp(49) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>gameplay.cpp(49) : error C2371: 'weapons' : redefinition; different basic types
1>        gameplay.cpp(48) : see declaration of 'weapons'
1>gameplay.cpp(49) : error C2440: 'initializing' : cannot convert from 'machineGun *' to 'int []'
1>        There are no conversions to array types, although there are conversions to references or pointers to arrays
1>gameplay.cpp(50) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>gameplay.cpp(50) : error C2369: 'weapons' : redefinition; different subscripts
1>        gameplay.cpp(48) : see declaration of 'weapons'
1>gameplay.cpp(50) : error C2440: 'initializing' : cannot convert from 'flamer *' to 'int [1]'
1>        There are no conversions to array types, although there are conversions to references or pointers to arrays




我采用了另一种不同的方法并得到了一些不同的错误。我仍然很不确定这一切是如何粘合在一起的。

//Weapon variables
const int totalWeapons = 2;
int currentWeapon = 1;
weapon weapons[totalWeapons] = {new machineGun, new flamer};

有错误:

1>gameplay.cpp(48) : error C2275: 'machineGun' : illegal use of this type as an expression
1>        gameplay.h(36) : see declaration of 'machineGun'
1>gameplay.cpp(48) : error C2275: 'flamer' : illegal use of this type as an expression
1>        gameplay.h(41) : see declaration of 'flamer'




答案最终是这样的:

//Weapon variables
const int totalWeapons = 2;
int currentWeapon = 1;
weapon *weapons[totalWeapons] = {new machineGun, new flamer};

感谢所有帮助我解决这个问题的人!

最佳答案

#include <iostream>

class weapon {

 public:
  int fireRate;
  int bulletDamage;
  int range;
  int activeBullet;

 public:
  virtual void fire(void) {std::cout << "machine " << '\n';}
  virtual ~weapon() {std::cout << "destructor is virtual" << '\n';}
};

class machineGun: public weapon {
 public: 
  void fire(void) {std::cout << "machine gun firing" << '\n';}
  ~machineGun(void) { std::cout << "machine gun destroyed" << '\n';}
};

class flamer: public weapon {
 public: 
  void fire(void) {std::cout << "flamer firing" << '\n';}
  ~flamer(void) {std::cout << "flamer destroyed" << '\n';}
};

int main(void)
{
    const int count = 2;
    weapon *weapons[count];

    machineGun *a = new machineGun();
    flamer     *b = new flamer();

    weapons[0] = a;
    weapons[1] = b;

    weapons[0]->fire();
    weapons[1]->fire();

    delete a;
    delete b;

}

关于c++ - 是否可以拥有来自同一基类的不同对象的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4383805/

有关c++ - 是否可以拥有来自同一基类的不同对象的数组?的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  2. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  3. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  4. ruby-on-rails - 按天对 Mongoid 对象进行分组 - 2

    在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev

  5. ruby-on-rails - 在 Ruby 中循环遍历多个数组 - 2

    我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代

  6. ruby - 多次弹出/移动 ruby​​ 数组 - 2

    我的代码目前看起来像这样numbers=[1,2,3,4,5]defpop_threepop=[]3.times{pop有没有办法在一行中完成pop_three方法中的内容?我基本上想做类似numbers.slice(0,3)的事情,但要删除切片中的数组项。嗯...嗯,我想我刚刚意识到我可以试试slice! 最佳答案 是numbers.pop(3)或者numbers.shift(3)如果你想要另一边。 关于ruby-多次弹出/移动ruby​​数组,我们在StackOverflow上找到一

  7. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

  8. ruby - 将数组的内容转换为 int - 2

    我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]

  9. ruby - 我可以使用 Ruby 从 CSV 中删除列吗? - 2

    查看Ruby的CSV库的文档,我非常确定这是可能且简单的。我只需要使用Ruby删除CSV文件的前三列,但我没有成功运行它。 最佳答案 csv_table=CSV.read(file_path_in,:headers=>true)csv_table.delete("header_name")csv_table.to_csv#=>ThenewCSVinstringformat检查CSV::Table文档:http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV/Table.html

  10. ruby - Highline 询问方法不会使用同一行 - 2

    设置:狂欢ruby1.9.2高线(1.6.13)描述:我已经相当习惯在其他一些项目中使用highline,但已经有几个月没有使用它了。现在,在Ruby1.9.2上全新安装时,它似乎不允许在同一行回答提示。所以以前我会看到类似的东西:require"highline/import"ask"Whatisyourfavoritecolor?"并得到:Whatisyourfavoritecolor?|现在我看到类似的东西:Whatisyourfavoritecolor?|竖线(|)符号是我的终端光标。知道为什么会发生这种变化吗? 最佳答案

随机推荐