c++ - Is there any way in C++ to cast/copy a Parent class into a Child class?
问题描述
I receive a complicated object from a framework I can't really change:
Parent parent = framework.get();
I would like to add some attributes and methods to this parent:
class Child : public Parent {
public:
inline Child() {}
int extraVariable = 999;
int extraMethod() { return 666; }
};
Is there any way to 'cast' or copy an instantiated Parent into a Child class, other than manually copying all the attributes?
The python equivalent would be
class Child(Parent):
def extraMethod(self):
return 666
parent = framework.get()
parent.__class__ = Child
I realize C++ isn't python but I'm willing to hack it together (this is personal code, i.e. ugly is fine).
解决方案
You could add a converting constructor, or two, to Child
.
Example:
class Child : public Parent {
public:
// converting constructors
Child(const Parent& p) : Parent(p) {} // copy
Child(Parent&& p) : Parent(std::move(p)) {} // move
//...
}
推荐阅读
- java - 如何在我的 java 项目中寻址文件夹?
- java - Java 扫描仪的工作原理
- php - Blade Laravel 中的未定义变量
- sql - 如何选择一些具有空行或空行的列
- r - DT 根据单独的数据框将背景颜色应用于单元格
- git - 构建失败并出现错误:无法锁定 ref 'refs/remotes/origin/users/bill.roper/develop':位于 b10165 但预期为 5f
- flutter - 除非使用 Center 包装小部件,否则 Flutter 设置容器小部件的宽度和高度不起作用?为什么?
- javascript - 使用 Bootstrap 3.3 更改打印行顺序
- postgresql - 具有多列索引的 postgres 查询的执行时间很慢
- javascript - 嵌入表单并将其发布到另一个站点