【发布时间】:2014-03-03 07:50:31
【问题描述】:
说我有
class Parent
{};
class ChildOne : Parent
{};
class ChildTwo : Parent
{};
void SomeMethod(std::vector<Parent*>& parents);
我明白为什么我不能将std::vector<ChildOne*> 作为参数传递给SomeMethod,因为SomeMethod 可能是:
void SomeMethod(std::vector<Parent*>& parents)
{
parents.push_back(new ChildTwo);
}
这将是无效的。
但是为什么我不能将std::vector<ChildOne*> 作为参数传递给
void AnotherMethod(const std::vector<Parent*>& parents);
在这种情况下,我想不出会出什么问题,但我一定是错过了什么。
编辑:
为了澄清,我想知道为什么存在这个限制。在 C#(例如)中,这将编译(使用 IEnumerables)。我假设存在一个失败案例。
【问题讨论】:
-
如果允许可转换类型,这种转换会对性能产生严重影响。对于指针,无法断言类型安全(即,如果存在此功能,则转换
vector<Parent*> -> vector<void*>也将有效,因为指针不知道继承。这是一个严重的混乱。
标签: c++ inheritance vector