【问题标题】:Using std::for_each on polymorphic method in c++在 C++ 中的多态方法上使用 std::for_each
【发布时间】:2009-01-20 11:10:12
【问题描述】:

当使用 std::for_each 时,

class A;
vector<A*> VectorOfAPointers;

std::for_each(VectorOfAPointers.begin(), VectorOfAPointers.end(), std::mem_fun(&A::foo));

如果我们有继承自 A 并实现 foo() 的类,并且我们持有指向 A 的指针向量, 有没有办法在 foo() 上调用多态调用,而不是显式调用 A::foo()? 注意:我不能使用 boost,只能使用标准 STL。

谢谢, 加尔

【问题讨论】:

    标签: c++ stl vector polymorphism foreach


    【解决方案1】:

    它实际上是这样工作的。

    #include <algorithm>
    #include <iostream>
    #include <functional>
    #include <vector>
    
    struct A {
        virtual void foo() {
            std::cout << "A::foo()" << std::endl;
        }
    };
    struct B: public A {
        virtual void foo() {
            std::cout << "B::foo()" << std::endl;
        }
    };
    
    int main()
    {
        std::vector<A*> VectorOfAPointers;
        VectorOfAPointers.push_back(new B());
        std::for_each(VectorOfAPointers.begin(), VectorOfAPointers.end(), std::mem_fun(&A::foo));
        return 0;
    }
    

    打印

    B::foo()
    

    所以它完全符合您的要求。检查 virtual 关键字是否存在,很容易忘记它们。

    【讨论】:

      猜你喜欢
      • 2010-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-29
      • 1970-01-01
      • 2012-03-31
      • 2014-04-01
      相关资源
      最近更新 更多