【问题标题】:How do I create a list of objects in c ++ and use its methods? [duplicate]如何在 C++ 中创建对象列表并使用其方法? [复制]
【发布时间】:2021-02-17 13:30:54
【问题描述】:

我创建了这个类,我需要使用 for(迭代器)来输入值,它们不一定是 i,任何其他值,因为我需要使用列表:

#include <iostream>
#include <list>

using namespace std;
// 1ra clase base
class Person {
  int e;

 public:
  Person(int);
  void printDates();
};

Person::Person(int x) { e = x; }
void Person::printDates() { cout << e; }
int main() {
  list<Person> persons;
  for (int i = 0; i < 5; i++) {
    Person person(i);
    persons.push_front(person);
  }
  // for(int i = 0; i < 5; i++)
  // {
  //     hombres[i].printDates();
  // }
}

我需要使用 personDates 方法,以及您可以添加的任何其他方法,无论是在列表中还是在另一个列表中。

【问题讨论】:

  • for( auto&amp; person : persons) { // do something with person } 在线示例:https://ideone.com/8lEv0C
  • “输入值”是什么意思?什么是“personDates 方法”?你的意思是printDates()?您使用的 for 循环有什么问题?
  • 也许您需要for each loop
  • 谢谢你,写下你的答案,我会在答案中评价它@drescherjm
  • 你为什么还要使用std::list?请改用std::vector,因为它几乎在所有方面都更胜一筹。而且你不需要push_front

标签: c++


【解决方案1】:

问题是列表没有在容器中提供index

persons[i] // does not work for list (though it does work for vector).

所以你需要使用迭代器。
旧版本的 C++ 是这样完成的:

for(auto loop = persons.begin(); loop != persons.end(); ++loop) {
    loop->printDates();
}

在现代版本的 C++ 中,这被简化为:

for(auto& item: persons) {
    item.printDates();
}

【讨论】:

    猜你喜欢
    • 2015-10-24
    • 2021-07-23
    • 2017-02-13
    • 1970-01-01
    • 2019-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多