C ++:我如何避免“无效的协变返回类型”在继承类没有cast? [英] C++: How can I avoid "invalid covariant return type" in inherited classes without casting?

查看:415
本文介绍了C ++:我如何避免“无效的协变返回类型”在继承类没有cast?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个相当复杂的类层次结构,其中类是交叉的,取决于彼此:有两个抽象类A和C,分别包含返回C和A的实例的方法。在他们继承的类中,我想使用一个co-variant类型,在这种情况下是一个问题,因为我不知道一种方式来转发声明继承关系ship。

I have a quite complex class hierarchy in which the classes are cross-like depending on each other: There are two abstract classes A and C containing a method that returns an instance of C and A, respectively. In their inherited classes I want to use a co-variant type, which is in this case a problem since I don't know a way to forward-declare the inheritance relation ship.

我得到一个test.cpp:22:error:无效的协变量返回类型为'virtual D * B :: outC不知道D是C的子类。

I obtain a "test.cpp:22: error: invalid covariant return type for ‘virtual D* B::outC()’"-error since the compiler does not know that D is a subclass of C.

class C;

class A {
public:
        virtual C* outC() = 0;
};

class C {
public:
        virtual A* outA() = 0;
};


class D;

class B : public A {
public:
        D* outC();
};

class D : public C {
public:
        B* outA();
};

D* B::outC() {
        return new D();
}

B* D::outA() {
        return new B();
}



如果我将B :: outC()的返回类型更改为C *示例编译。有没有什么办法保持B *和D *作为返回类型在继承类中(这将是直观的,我有一种方法)?

If I change the return type of B::outC() to C* the example compiles. Is there any way to keep B* and D* as return types in the inherited classes (it would be intuitive to me that there is a way)?

推荐答案

我知道没有办法在C ++中直接耦合协变成员。

I know of no way of having directly coupled covariant members in C++. You'll have either to add a layer, or implement covariant return yourself.

对于第一个选项

class C;

class A {
public:
        virtual C* outC() = 0;
};

class C {
public:
        virtual A* outA() = 0;
};


class BI : public A {
public:
};

class D : public C {
public:
        BI* outA();
};

class B: public BI {
public:
        D* outC();
};

D* B::outC() {
        return new D();
}

BI* D::outA() {
        return new B();
}

和第二个

class C;

class A {
public:
        C* outC() { return do_outC(); }
        virtual C* do_outC() = 0;
};

class C {
public:
        virtual A* outA() = 0;
};


class D;

class B : public A {
public:
        D* outC();
        virtual C* do_outC();
};

class D : public C {
public:
        B* outA();
};

D* B::outC() {
        return static_cast<D*>(do_outC());
}

C* B::do_outC() {
        return new D();
}

B* D::outA() {
        return new B();
}

注意,第二个选项是由编译器隐式完成的static检查static_cast是否有效)。

Note that this second option is what is done implicitly by the compiler (with some static checks that the static_cast is valid).

这篇关于C ++:我如何避免“无效的协变返回类型”在继承类没有cast?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆