gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 19:50:46 26 4
gpt4 key购买 nike

当使用 std::for_each 时,

class A;
vector<A*> VectorOfAPointers;

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

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

谢谢,加尔

最佳答案

它实际上是这样工作的。

#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 关键字是否存在,但很容易忘记它们。

关于c++ - 在 C++ 中的多态方法上使用 std::for_each,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/460847/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com