如何在不使用继承的情况下编译用户定义类的指针

时间:2013-02-13 07:21:14

标签: c++ pointers inheritance casting

我有两个用户定义的类:

class A:class Base
{
type x;
doSomething();
}

class B
{
type x;
doSomething();
}

我还有一个函数,它获取Base类型的变量,并使用dynamic_cast将其转换为A类并使用doSomething()。

class D : class Base2
{
    D(Base _base1):Base2(Base _base1)
    {
         //here is the actual problem
    }
    void foo()
    {
       //b is a private member of class Base2 of type Base
       A *a=dynamic_cast(b);
       A->doSomething();
    }
}

但我希望将B传递给此函数,同时我不希望B从Base继承。

p.s我无权更改Base

这怎么可能?

1 个答案:

答案 0 :(得分:3)

在不安全的情况下在不相关的类之间进行转换。实现我认为您尝试做的最安全的方法是使用功能模板:

template <typename T>
void foo(const T& b)
{
   b.doSomething();
}