派生类的reinterpret

派生类的reinterpret

本文介绍了派生类的reinterpret_cast向量到基类的向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个第三方类,例如,类 A ,并且有一个函数从同一个第三方中接受类 A 的向量,例如 f3()(请参见下面的简化程序).

I have a 3rd-party class, say, class A, and a function accepting vector of class A from the same 3rd-party, say f3() (See simplified program below).

为了更轻松地使用 A ,我创建了一个派生类 B .我程序的许多部分都使用了 B 类.

For easier use of A, I created a derived class B. Many part of my program used class B.

问题是,如何以向量 B 作为参数来调用 f3()?像下面的程序一样,强制转换 f3()的参数是否是一种好习惯?

The question is, how can I call f3() with a vector of B as its argument?Is a forced casting in the argument of f3() like the program below a good practice?

#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

// a 3rd-party class
class A
{
public:
    int n;
    void f1();
};

// my class
class B: public A
{
public:
    void f2();
};

// a 3rd-party function
void f3(std::vector<A> &a);

int main()
{
    std::vector<B> y;

    y.push_back(B());
    y.push_back(B());
    y.push_back(B());
    y.push_back(B());

    f3(*(vector<A>*)(&y));  // Is this a good practice?
    cout << y[3].n << endl;
    return 0;
}

请注意,出于兼容性考虑,当 B 继承自 A .但是,与 A 相比,类 B 具有更多的方法.

Note that, for compatibility, I purposely make class B to have no more variables than class A, when B inherits from A. However, Class B does have more methods than A.

是否可以保证 sizeof(A) sizeof(B)相同,以便我们的矢量转换有效?

Will it guarantee that sizeof(A) is the same as sizeof(B), so that our cast of vector will work?

我正在使用C ++ 03

I am working on C++03

推荐答案

要从您的代码中回答问题:

To answer the question from your code :

不,这实际上是一个非常糟糕的做法,它会导致不确定的行为.

No, it's actually a very bad practice , and it will lead to undefined behavior.

如果sizeof(A)等于sizeof(B),则考虑到从B派生并在f3内使用的所有函数都是虚函数和非内联函数,您的代码可能会正常工作.

If sizeof(A) is equal to sizeof(B) your code might end up working ,considering that all functions derived in B and used inside f3 are virtual and non inline.

如果最终使用了这样的代码,请确保永远不要向B类添加另一个虚函数/成员变量.

If you end up using such code , make sure you will never ever add another virtual function / member variable to the B class .

如果您想绕过此限制(f3第三方函数仅接受A的向量),请尝试使B成为复合而不是派生(如果您不访问A的受保护成员):

If you want a way to bypass this limitation (f3 third party function only accepts vector of A ) , try making B a composite rather then a derived (if you are not accessing protected members of A ) :

class A
{
   public:
   int n;
   void f1();
}
class B
{
  public:
      B (const A& a); // dependency injection
      void f2();
      A  myA; // bad practice, should be private with getter /setter
}

这样,您将隔离A的特定功能.

This way you are isolating the A specific functionality / features.

Ofc仍然需要根据B中包含的对象手动创建A对象的向量(不能传递B的向量).

Ofc you will still need to manually make a vector of A objects made from the objects contained in B (you cannot pass a vector of B).

这篇关于派生类的reinterpret_cast向量到基类的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 06:10