在 c++ 中的多态方法上使用 std::for_each

发布于 2024-07-11 19:44:50 字数 338 浏览 4 评论 0原文

当使用 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。

谢谢, 加尔

When using the std::for_each,

class A;
vector<A*> VectorOfAPointers;

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

If we have classes inheriting from A and implementing foo(), and we hold a vector of pointers to A,
is there any way to call a polymorphic call on foo(), rather then explicitly calling A::foo()?
Note: I can't use boost, only standard STL.

Thanks,
Gal

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

地狱即天堂 2024-07-18 19:44:50

它实际上是这样工作的。

#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()

所以它完全符合你的要求。 不过,请检查虚拟关键字是否存在,但很容易忘记它们。

It actually works this way.

#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;
}

prints

B::foo()

So it does exactly what you want. Check that virtual keywords are present though, it's easy to forget them.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文