c++ - 如何通过 vector 调用方法?

标签 c++ stl vector

如何调用存储在 vector 中的对象的方法?以下代码失败...

    ClassA* class_derived_a = new ClassDerivedA;
    ClassA* class_another_a = new ClassAnotherDerivedA;



  vector<ClassA*> test_vector;

  test_vector.push_back(class_derived_a);
  test_vector.push_back(class_another_a);

 for (vector<ClassA*>::iterator it = test_vector.begin(); it != test_vector.end(); it++)
    it->printOutput();

代码检索到以下错误:

test3.cpp:47: error: request for member ‘printOutput’ in ‘* it.__gnu_cxx::__normal_iterator<_Iterator, _Container>::operator-> with _Iterator = ClassA**, _Container = std::vector >’, which is of non-class type ‘ClassA*’

问题似乎是it->printOutput(); 但目前我不知道如何正确调用该方法,有人知道吗?

问候麦基

最佳答案

vector 中的东西是指针。你需要:

(*it)->printOutput();

它取消引用迭代器以从 vector 中获取指针,然后在指针上使用 -> 来调用函数。如果 vector 包含对象而不是指针,则您在问题中显示的语法将起作用,在这种情况下,迭代器就像指向这些对象之一的指针一样。

关于c++ - 如何通过 vector 调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2833257/

相关文章:

c++ - 如何使用二维 vector 表示 Dijkstra 算法中的边权重

c++ - 使用指向数据成员的指针作为非类型模板参数

c++ - 如何在字符串中查找字符 "\"?

C++通过引用传递常量值

c++ - 列出迭代段错误

r - 在向量中找到 n 个最接近位置 t 的非 NA 值

c++ - Visual Studio 中的堆栈大小较小

c++ - 如何防止通过 'new' 运算符分配类? (我想确保我的 RAII 类始终分配在堆栈上。)

C++ STL Map vs Vector 速度

c++ - 您将如何取消引用 vector 迭代器