问题描述
说我有两个类 A
和 B
,以及 A
如下:
class A {
int foo;
int bar;
void someMethod();
};
class B {
uint foo;
uint bar;
void someOtherMethod();
};
std :: vector< A> va;
,我要将 va
解释为因为 int
和 uint
是可重新解释的。
做重新解释的最佳做法是什么?
例如,如果我要调用 va
上的 someOtherMethod()
,我可以做((std :: vector< B> *)(& va)) - > someOtherMethod()
。但它是最好的做法吗?
在我看来, reinterpret_cast< std :: vector< B& >(va).someOtherMethod()
无效。
此外,我正在使用C ++ 03。 >
- UPDATE -
很抱歉我对我自己的问题有误解。
然而我的问题会与这个不一样。因此,我创建了另一个问题 。
我会很快关闭这个问题:这个问题可以看作一个独立的问题,我认为下面的答案是足够好接受。 p>
不要。任何你认为你可以做到这一点,导致未定义的行为。创建一个新的向量并复制这些值。
Say I have two classes A
and B
, and a vector of class A
as below:
class A {
int foo;
int bar;
void someMethod();
};
class B {
uint foo;
uint bar;
void someOtherMethod();
};
std::vector<A> va;
and I want to interpret va
as a vector of B, since int
and uint
are re-interpretable.
What is the best practice to do the re-interpretation?For example, if I want to invoke someOtherMethod()
on va
, I can do ((std::vector<B> *)(&va))->someOtherMethod()
. But is it the best practice?
It seems to me that reinterpret_cast<std::vector<B> >(va).someOtherMethod()
does NOT work.
In addition, I am working on C++03.
-- UPDATE --
Sorry for my misinterpret of my own question.Yet my question will be a lot different than this one. So I created another question here.
I will close this question soon: This question can be seen as an independent question, and I think one of the answers below is good enough to be accepted.
Don't. Any way you think you can do it results in undefined behaviour. Create a new vector and copy over the values.
这篇关于reinterpret_cast类A的向量到类B的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!