我有两个用户定义的类:
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
这怎么可能?
最佳答案
在不相关的类之间进行转换是不安全的。实现我认为您想要做的事情的最安全方法是使用函数模板:
template <typename T>
void foo(const T& b)
{
b.doSomething();
}
关于c++ - 如何在不使用继承的情况下转换用户定义类的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14848381/