【发布时间】:2023-02-16 17:21:59
【问题描述】:
这是代码:
#include <iostream>
class Interface_A
{
public:virtual bool dothething () = 0;
};
class Inherit_B:public Interface_A
{
bool dothething ()
{
std::cout << "Doing the thing in B\n";
return true;
}
};
class Inherit_C:public Interface_A
{
bool dothething ()
{
std::cout << "Doing the thing in C\n";
return true;
}
};
/**This works */
Interface_A& makeBC ()
{
#ifdef make_B
return *(new Inherit_B ());
#elif make_C
return *(new Inherit_C());
#endif
}
/**This doesn't work
Interface_A makeC ()
{
#ifdef make_B
return ((Interface_A) (new Inherit_B ()));
#elif make_C
return ((Interface_A) (new Inherit_C ()));
#endif
}
*/
int main ()
{
Interface_A& obj = makeBC ();
obj.dothething();
// ultimate goal is to make a vector of type <Interface_A&>
return 0;
}
我想最终创建一个类型为 <Interface_A&> 的向量,但我似乎无法找到一种方法来做到这一点。创建 <Interface_A> 类型的向量也可以,但据我所知,c++ 不允许创建对抽象类型的指针引用。
我不能使用返回类型 Inherit_B 因为 Interface_A 被多个类继承并且活动类是在编译时确定的。
我不能使用智能指针,因为性能是代码的一个极其关键的方面。
我如何为此制定通用解决方案?
【问题讨论】:
-
std::vector<Interface_A*>到底有什么问题?或者更好的std::vector<unique_ptr<Interface_A>>?
标签: c++ c++11 pointers interface pass-by-reference