【问题标题】:How to access vector class array methods in c++ [closed]如何在 C++ 中访问向量类数组方法 [关闭]
【发布时间】:2016-11-09 19:36:54
【问题描述】:
class Bird{

public:
    void init();
    Bird();//constructor
    void foo();//its defined somewhere
};


int _tmain(int argc, _TCHAR* argv[])
{
    std::vector <Bird> B[51];

    for (int i = 0; i < 51; i++)
       B[i].foo();
}

似乎矢量是一种安全且现代的方式来安全地生成 51 个对象。

假设我从 Bird 类创建了一个对象数组。并想使用每个对象的方法。 (我不能使用静态对象数组,因为我以后必须交换数组成员。)



(自 2000 年以来我没有使用 C++。现在我必须使用)

【问题讨论】:

  • 你有一个向量数组。看起来你想要一个向量。
  • vector 似乎是在 C++ 中使用动态数组的现代方式。我希望它使用。所以你有一个解决方案而不是 unrate 问题?
  • 使用[] 创建了一个包含 51 个向量的数组。要拥有一个包含 51 个元素的向量,请使用 std::vector &lt;Bird&gt; B(51);
  • 我只想指出std::vector 已经存在了大约 15 年,如果算上最初的 STL 实现,甚至更长...所以“现代”可能不是我会选择的词.

标签: c++ visual-c++ stdvector icc


【解决方案1】:

正如布先生的反应一样。

class Bird{

public:
    void init();
    Bird();//constructor
    void foo();//its defined somewhere
};


int _tmain(int argc, _TCHAR* argv[])
{
    std::vector <Bird> B(51); // fixed line

    for (int i = 0; i < 51; i++)
       B[i].foo();
}

【讨论】:

    猜你喜欢
    • 2023-04-01
    • 1970-01-01
    • 2019-06-25
    • 2014-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多