【问题标题】:Updating values of objects within array using object method使用对象方法更新数组中对象的值
【发布时间】:2015-06-16 08:50:08
【问题描述】:

我花了一些时间研究这个问题,虽然我看到了类似的问题,但没有一个对我的问题有用。

我的问题是,当我更新这些对象时,只有最后一个正确更新。另一个(或更多)要么根本不移动(调试器显示它们正在被调用,但即使输入非零,更新函数也不做任何事情),或者即使最后一个展示了移动并且没有正确碰撞正确的行为。我真的一直在试图弄清楚如何让它们全部正确更新。

发生的事情是我涉及 3 个课程。应用程序、目标和点。主函数调用 Application.run(),它处理所有其他对象/方法的运行和跟踪。

所以在应用程序中,我有一个目标数组 TargetsInScene。我在这里初始化它:

void Application::InitTargets() {
    TargetsInScene = (Target **) malloc(sizeof(Target *)*MaxTargets);
    TargetCount = 0;
    // initialize some static class variables here

    TargetsInScene[TargetCount] = new Target(1);
    TargetCount++;
    TargetsInScene[TargetCount] = new Target(1);
    TargetCount++;
}

Application::Application(int screenX, int screenY) {
    InitTargets();
}

然后 Application.Run() 调用这个:

void C_Application::UpdateTargets() {
    for (int i = 0; i < TargetCount; i++)
    {
        TargetsInScene[i]->Update();
    }

更新函数如下所示:

void Target::Update() {

   // changes direction if it hits something
   checkCollisions()

   //coord is a Point obj and update +='s the new values to its x and y values
   coord.update(dir*speed, dir*speed);
}

【问题讨论】:

  • 不确定为什么要使用数组而不是 std::vector&lt;Target&gt;,这将是一种更好的处理方式。但是,我在您发布的当前代码中看不到任何错误(尽管您遗漏了很多代码)。
  • Target 类成员变量没有声明为 static 是吗?
  • 我也尝试过具有完全相同结果的向量。并且一些类变量是静态的,但我试图改变的不是。
  • 你检查过 UpdateClocks 中的 TargetCount 了吗?

标签: c++ arrays object


【解决方案1】:

使用像这样的矢量可以工作,并且更清洁和节省。

  1 #include <iostream>
  2 #include <vector>
  3 
  4 struct Target {
  5     void update()
  6     {
  7         std::cout << "Updating: " << id << std::endl;
  8      
  9     }
 10     Target(int i) : id(i){};
 11 
 12     int id;
 13 };
 14 
 15 int main()
 16 {
 17     std::vector<Target> TargetsInScene;
 18     for (int i = 0; i < 4; ++i) { 
 19         TargetsInScene.emplace_back(i);
 20     } 
 21     for (auto& target : TargetsInScene) {
 22         target.update();
 23     }   
 24 }   

【讨论】:

    猜你喜欢
    • 2021-07-08
    • 2021-04-29
    • 1970-01-01
    • 1970-01-01
    • 2017-10-04
    • 2021-11-27
    • 2021-05-29
    • 1970-01-01
    • 2022-11-16
    相关资源
    最近更新 更多