简体   繁体   English

多态性,为什么我不能这样做?

[英]Polymorphism, why can't I do this?

class BaseA
{
}

class B : public BaseA
{
}

template <class T>
class C : public vector<T>
{
}

void someFunction (void)
{
    C<B> myClass;

    // I can't seem to do this...is it not possible?
    vector<BaseA> converted = ((vector<BaseA>) myClass);
}

See comment in code for what I am trying to do.请参阅代码中的评论以了解我正在尝试做的事情。

A vector of B isn't a vector of A even if B is an A (I assume a mixup between A and BaseA) B 的向量不是 A 的向量,即使 B 是 A(我假设 A 和 BaseA 之间存在混淆)

Try尝试

vector<A> converted(myClass.begin(), myClass.end());

which is probably what you want to express.这可能是你想要表达的。

(BTW inheriting from vector is bad idea in general , it isn't designed for that.) (顺便说一句,从 vector 继承通常是个坏主意,它不是为此而设计的。)

C<B> and vector<A> are completely unrelated types and you would have to explicitly define such a conversion (eg template <typename TargetValueType> explicit operator vector<TargetValueType> () {... } ). C<B>vector<A>是完全不相关的类型,您必须显式定义这样的转换(例如template <typename TargetValueType> explicit operator vector<TargetValueType> () {... } )。

If such conversion is an uncommon task, something that is not really natural to the nature of your class, it might be preferable to use a range constructor (see AProgrammer's answer).如果这种转换是一项不常见的任务,对于您的 class 的性质来说并不是很自然,那么使用范围构造函数可能更可取(请参阅 AProgrammer 的回答)。

Also: If vector is std::vector , deriving from it is not a good idea.另外:如果vectorstd::vector ,从它派生不是一个好主意。 It isn't defined as a base class, and typically you should prefer containment over derivation (as it imposes looser coupling on your clients).它未定义为基数 class,通常您应该更喜欢包含而不是派生(因为它对您的客户端施加了更松散的耦合)。

No way no how.没办法没办法。 Imagine if you had another class, X , derived from BaseA .想象一下,如果您有另一个 class, X派生自BaseA If you could get your converted object, you could insert instances of X in it, even though the original object wouldn't allow it.如果您可以获得converted后的 object,则可以在其中插入X的实例,即使原始 object 不允许这样做。 You'd be breaking the semantics of your variables.您会破坏变量的语义。

Incidentally you can do this in Java where they have no real sense of generics, but in a strongly typed generic language like C# or C++ you won't be able to do it (with the one exception in C#, but you shouldn't use it in this case anyway).顺便说一下,您可以在 Java 中执行此操作,他们没有真正意义上的 generics,但是在强类型的通用语言中,如 C# 或 C++,您将无法执行此操作(C# 中有一个例外,但您不应该使用无论如何在这种情况下)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM