如何在C ++中实现对私有基类的转换 [英] how to implement casting to a private base class in C++

查看:66
本文介绍了如何在C ++中实现对私有基类的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在C ++中实现对私有基类的转换?我不想使用黑客,例如添加朋友等。定义公共类型转换运算符不起作用。

How to implement casting to a private base class in C++? I don't want to use hacks such as adding a friend etc. Defining public casting operator does not work.

编辑:

例如,我有:

class A {
//base class
}

class AX : private A {
//a child
}

class AY : private A {
//another specialized child
}

class B {
//base class
void do (A a) {//do
    }
}

class BX : private B {
//a child
void do (AX a) {
     B::do( static_cast <A> (a) );
    }
}

class BY : private B {
//another specialized child
void do (AY a) {
    B::do( static_cast <A> (a) );
    }
}

EDIT2

为什么要这样做?

假设我必须定义一些重量级的属性,可以是多个类似的属性类型(例如VelocityX VelocityY等)。然后,我希望能够拥有可以具有这些属性的任何集合的类。如果要处理这些属性,很明显,我宁愿将它们强制转换为它们的基本类型,而不是为每个变体添加实现。我不使用公共继承,因为与隐式可见私有接口相比,最好在需要的地方进行显式转换。这不是一个真正的问题,但是我想有一个解决方案:)

Suppose I have to define some property which is quite heavyweight and can be of several similar types (like VelocityX VelocityY etc). Then I want to be able to have classes which can have any set of these properties. If I want to process these properties, it is obvious, that I'd rather cast them to their base type than to add an implementation for each variation. I do not use public inheritance because it's better to explicitly cast where needed than to have the private interface implicitly visible. Not a real problem but I'd like to have a solution :)

推荐答案

如果定义公共转换运算符不起作用,您可以尝试使用常规功能:

If defining a public casting operator does not work, you can try with a regular function:

class D: private B {
    public:
        B& asB() { return static_cast<B&>(*this); }
};
...
D d;
d.asB().methodInB();
...

无论如何,这是什么意思?如果 D 是从 B 私下获得的,则您不应该使用 D 作为外部的 B

Anyway, what is the point? If D derives privately from B, then you are not supposed to use a D as a B from the outside.

这篇关于如何在C ++中实现对私有基类的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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