投射指向对象的指针数组 [英] Casting array of pointers to objects

查看:127
本文介绍了投射指向对象的指针数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果 B A 的子类。

我在 main()

B** b = new B*[10];
... // some algorithm that does b[i] = new B(..);

所以我有一个指向数组的对象 B

So I have an array of pointers to objects B.

然后我有一个函数:

void f(A** foo);

如果在main中,我会: f(b); 我得到一个警告,但显然如果我这样做: f((A **)b); ,我不。

If in main, I do: f(b); I get a warning, but obviously if I do: f((A**)b);, I don't.

(A **)它有点讨厌。我想知道是否有更优雅的方式在C + +,至少做类型检查 dynamic_cast

The (A**) its a bit nasty. I was wondering if there's a more elegant way in C++ that at least do type checking as dynamic_cast.

foo来排序(只使用交换)类型A或子类的对象数组。所以做一个通用的排序算法。我希望现在你能更好地理解我的问题。

I want foo to sort (only using swaps) arrays of objects of type A or subclass.. so make a generic sorting algorithm. I hope now you understand better my problem.

推荐答案

如果你试图隐式投射一个警告或错误, B ** A ** :这样做是不安全的。

There's a reason you get a warning or error if you try to implicitly cast a B** to a A**: it's not safe to do so.

将数组引用为 A ** 允许将指针指向 A 对象内。对于 B * 的数组,这是错误的,因此转换是不安全的。

Referring to the array as a A** allows you to put pointers to A objects inside. For an array of B* this is wrong and therefor the cast is unsafe.

也许 f 将更好地作为模板函数:

Maybe f would better be a template function:

template<typename T>
void f(T **array) {
   ...
}

这篇关于投射指向对象的指针数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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