简体   繁体   English

排印矢量 <object> 在C ++中?

[英]Typcasting vector<object> in C++?

I have two classes, obstacle and boid, boid inherits from obstacle. 我有两个类,障碍和博伊德,博伊德从障碍继承。

Now I want to write some functions that can work with objects of both classes, so that passing vector<boid> does work as well as vector<obstacle> . 现在,我想编写一些可以与两个类的对象一起使用的函数,以便传递vector<boid>vector<obstacle>

When I typecast like this and try to access the size of the vector I get a number of 1840700394 instead of 60: 当我像这样打字时,尝试访问向量的大小时,我得到的数字是1840700394,而不是60:

vector<boid>* boids; ....
cout << ((vector<obstacle>*)boids)->size() << endl;

I also tryed "reinterpret_cast" but same problem. 我也尝试过“ reinterpret_cast”,但是同样的问题。

C++ templates are not like C# and Java generics. C ++模板与C#和Java泛型不同。 A template instantiation is a complete class, and is not related to other template instantiations in any way whatsoever. 模板实例化是一个完整的类,并且与任何其他模板实例化都没有任何关系。 One cannot cast between them. 一个人不能在他们之间投掷。

(Side Note: If you were using static_cast instead it would have caught this for you....) (侧面注意:如果您使用的是static_cast ,它将为您抓到这个...。)

You can't cast a vector to a different type of vector like that. 您不能将向量转换为其他类型的向量。 If you need a generic function that works with both types of objects, you can use a function template. 如果您需要可同时使用两种对象的通用函数,则可以使用函数模板。

template <typename T>
void func(const std::vector<T>& vec)
{
  ....
}

This function will accept a vector containing any type of object. 此函数将接受包含任何类型的对象的向量。

Also, see Roger Pate's comment below. 另外,请参阅下面的Roger Pate的评论。 You can let the function accept any type of container (or any object that implements the appropriate semantics) by just saying: 您可以通过以下方式让函数接受任何类型的容器(或实现适当语义的任何对象):

template <typename T>
void func(const T& container) { ... }

A simple way to solve this kind of problem is to use a std::vector<obstacle *> . 解决此类问题的一种简单方法是使用std::vector<obstacle *> Then you can populate your vector with pointers to any object that inherits from obstacle. 然后,您可以使用指向从障碍继承的任何对象的指针填充向量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM