reinterpret_cast vector of class A to vector of class B

前端 未结 3 672
抹茶落季
抹茶落季 2020-12-22 08:21

Say I have two classes A and B, and a vector of class A as below:

class A {
    int foo;
    int bar;
    void someMet         


        
3条回答
  •  半阙折子戏
    2020-12-22 08:53

    The program behaviour is undefined since the types are unrelated.

    One solution is to write a cast operator to copy a class B instance to a class A instance. In class B, write

    operator A() const
    {
        A a;
        a.foo = this->foo; // ToDo - check `this->foo` is an appropriate size
        a.bar = this->bar; // ToDo - check `this->bar` is an appropriate size
        return a; // compiler will elide the value copy
    }
    

提交回复
热议问题