gpt4 book ai didi

c++ - 如何在不使用继承的情况下转换用户定义类的指针

转载 作者:行者123 更新时间:2023-11-28 00:49:29 25 4
gpt4 key购买 nike

我有两个用户定义的类:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com