参数中的C ++协方差 [英] C++ covariance in parameters
本文介绍了参数中的C ++协方差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道为什么C ++不支持参数中的协方差,例如下面的示例,或者如果有一种方法来实现它?
I wanted to know why C++ does not support co-variance in parameters like in example below or if there is a way to achieve it?
class base {
public:
virtual base* func(base * ptr) { return new base(); }
};
class derived : public base {
public:
virtual derived* func(derived * ptr) override { return new derived(); } //not allowed
};
推荐答案
返回类型是允许的,因为 derived
继承自 base
,但是函数参数不能工作 - 不是所有 base
实例也将是派生
。在 func
被指向 base
的指针调用的情况下应该发生的,参数不是 derived
?最派生的实现不可调用。
The return type is permissible since derived
inherits from base
, but the function parameter can't work - not all base
instances will be a derived
also. What's supposed to happen in the cases where func
is called on a pointer to base
with a parameter that's not a derived
? The most derived implementation isn't callable.
这篇关于参数中的C ++协方差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文