【问题标题】:How can I access the objects in a vector of class objects in C++?如何在 C++ 中访问类对象向量中的对象?
【发布时间】:2020-04-14 21:29:39
【问题描述】:

我有一个名为 DriverVect 的向量,它是 Drivers 类的成员。 DriverVect 是类 Driver 对象(不是 Drivers)的向量。我是一名初学者程序员,我正在尝试从我的主函数访问和修改 DriverVect 中的元素。

编辑:最小的可重现示例:

#include <vector>
using namespace std;

class Driver {
  public:
    void SetID(int DriverID);
  int GetID() const;

  private:
    int ID;
};

class Drivers {
  public:
    vector < Driver > DriverVect;
};

int main() {
  Drivers d;
  cout << DriverVect.at(1) << endl;
}

【问题讨论】:

  • 那么,你有class Drivers { std::vector&lt;Driver&gt; DriverVect; };?向我们展示代码。
  • Start with this。修改该代码,以便您可以发布显示问题的minimal reproducible example
  • @absoluteBeginner -- 获取我在链接中的代码,添加到它,从中删除代码,然后以这种方式重现错误。我编译的代码没有问题,因此请求您获取工作代码,并打破它,以便您可以在此处发布损坏的代码供我们诊断。要么这样,要么从该代码中了解您的错误是什么并自己解决问题。
  • @absoluteBeginner 并将生成的minimal reproducible example 通过editing 问题放入您的问题中。不要把它作为评论。阅读有关“minimal reproducible example”的链接。您当前的代码不是那样。
  • 您的DriverVect 似乎是public。唯一的问题是您尝试在没有d 的情况下访问它。尝试Driver&amp; driver = d.DriverVect.at(1);(在您添加两个Drivers 之后),您将获得对第二个Driver 的引用。要像您尝试的那样打印它,您必须为 std::ostream&amp; operator&lt;&lt;(std::ostream&amp;, const Driver&amp;); 添加重载

标签: c++ class vector


【解决方案1】:

要修改向量的元素,需要通过引用来访问它们

auto &element = vector[i];

然后element 被绑定到向量中的元素,以同样的方式存储一个指针。

【讨论】:

  • 一旦提问者提供了一个可回答的问题,猜测被证明是错误的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多