[英]Invoke unique functions of derived classes from a vector of pointers to base class objects
#include <iostream>
#include <vector>
using namespace std;
class Base
{
public:
void speak() { cout << "Hello!"; }
};
class Derived1 : public Base
{
public:
void func1() { cout << "I'm a function!"; }
};
class Derived2 : public Base
{
public:
void func2() { cout << "I'm also a function!"; }
};
int main()
{
vector<Base*> v = { new Derived1(), new Derived2(), new Derived1(), new Derived2() //, ...
};
// For each Derived1 object invoke func1() and for each Derived2 object invoke func2()
}
Base is not polymorphic (no virtual function). Base不是多态的(没有虚函数)。 From these conditions how can I be able to invoke func1 for each Derived1 object and func2 for each Derived2 object in v?
从这些条件出发,我如何能够为v中的每个Derived1对象调用func1并为每个Derived2对象调用func2?
"Base is not polymorphic (no
virtual
function)."“基数不是多态的(没有
virtual
函数)。”
You still can do a static_cast<Derived1>(v[0])
/ static_cast<Derived2>(v[1])
, aso, as long you're sure what you'll get at a particular index. 仍然可以执行
static_cast<Derived1>(v[0])
/ static_cast<Derived2>(v[1])
,只要您确定在特定索引下会得到什么。
As-is, it's impossible. 照原样,这是不可能的。 You can't do
dynamic_cast
, no member that indicates one type or the other. 您不能执行
dynamic_cast
,没有成员可以指示一种类型或另一种类型。 There's absolutely no way to distinguish given a Base*
whether it's a Derived1*
or a Derived2*
. 绝对没有办法区分给定的
Base*
是Derived1*
还是Derived2*
。
You would have to do one of: 您将必须执行以下一项操作:
Add a virtual void func() = 0;
添加
virtual void func() = 0;
that the two different classes would override. 两个不同的类将被覆盖。
Add a member variable of type std::function<void()>
that would be set in the Base
constructor differently by the two Derived
classes. 添加一个类型为
std::function<void()>
的成员变量,该变量将在Base
构造函数中由两个Derived
类进行不同的设置。
Add a member variable that's an enum to indicate which Derived
it is, so that you could do a switch externally to do a safe static_cast
. 添加一个成员变量,该变量是一个枚举,以指示它是哪个
Derived
的,以便您可以在外部进行切换以执行安全的static_cast
。
Add a virtual ~Base()
so that that instead of a switch, you would do dynamic_cast
s. 添加一个
virtual ~Base()
以便您执行dynamic_cast
而不是进行开关。
Not actually have either Derived1
or Derived2
inherit from Base
, but instead have a variant<Derived1, Derived2>
. 实际上没有从
Base
继承Derived1
或Derived2
,而是有一个variant<Derived1, Derived2>
。
??? ???
Profit. 利润。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.