C++将派生类强制转换为基类型并返回派生类

C++ casting derived class to base type and back to derived

本文关键字:派生 基类 类型 返回 C++ 转换      更新时间:2023-10-16

我有一个遗留类a,我想扩展它(添加另一个变量),但由于该代码已经在生产中,向面向用户的类添加变量将破坏二进制兼容性。我试着用一些选角来让它发挥作用,但我遇到了一些问题。

#include <iostream>
#include <chrono>
#include <thread>
#include <cassert>
using std::cout;
using std::endl;
class A {
    public:
    int a;
    A() {
        cout<<"A Constructed"<<endl;
    }
    ~A() {
        cout<<"A Destructed"<<endl;
    }
};
class B : public A {
    public:
    int b;
    B() {
        cout<<"B Constructed"<<endl;
        b = 10;
    }
};
int main()
{
    B obj1;
    A obj2 = obj1;
    cout << "value is " << ((B*)&obj2)->b << endl;
}

我希望这个值是10,因为我在B的构造函数中设置了它,但实际上我得到了0。有没有办法解决这个问题,得到10分。

Output:-
./a.out
A Constructed
B Constructed
value is 0
A Destructed
A Destructed

初始化

B obj1;
A obj2 = obj1;

…复制构造obj2,并将对B对象的引用传递给该构造函数。在构造函数内部,它被视为(仅)A对象。这称为切片

如果A对象在整个代码中被视为值对象,那么除非可以修改类A,否则不能直接在其中添加状态。

修复此行

A obj2 = obj1;

成为

A &obj2 = obj1;

因为使用原始代码,您可以调用默认的复制构造函数A::A(const A& other)