C++将派生类强制转换为基类型并返回派生类
C++ casting derived class to base type and back to derived
我有一个遗留类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)
相关文章:
- 如何通过派生类函数更改基类中的向量
- 如何使用基类指针引用派生类成员
- 使用基类指针创建对象时,缺少派生类析构函数
- 如何引用基类的派生类?
- 如果基类包含双指针成员,则派生类的构造函数
- 为什么此派生对象无法访问基类的后递减方法?
- 使用基类中的派生方法运行线程,而无需使用模板
- 是否可以使用基类非虚拟方法中的派生类虚拟方法?
- C++重载函数,一个采用基类的参数,另一个采用派生类的参数
- 在派生类中使用基类的私有成员变量的最佳方法
- 基类和派生类的多态赋值运算符
- 如何在从抽象基派生的类中实现相同的方法?
- 基类的填充将被复制到派生类中
- 如何在不使用指针的情况下将派生类的对象作为参数传递给基类中的函数?
- 指向基类派生类的 std::unique_ptr 的指针
- 为什么基类数据在派生类数据之前初始化
- c++ 派生基类 Friend 函数访问父级上的私有函数
- 如何将基类替换为派生基类
- 当基类未指定构造函数时,如何使用仅具有带参数的构造函数的类派生基类?
- 解析公用派生基类模板中的函数模板名称时出错"Not declared in this scope"