c++ - 简单的 C++ 向下转型不适用于简单的类
问题描述
我正在尝试创建一个OpenFile
表示打开文件的泛型,我可以在我的实现中向下转换,它使用自己的方式来保存打开的文件。
#include <fstream>
#include <memory>
class OpenFile {
};
class File : public OpenFile
{
public:
std::unique_ptr<std::ofstream> file;
};
int main()
{
OpenFile file;
static_cast<File>(file).file;
return 0;
}
但是我得到
main.cpp:28:27: error: no matching function for call to ‘File::File(OpenFile&)’
static_cast<File>(file).file;
我认为它与复制构造函数有关,但它不应该在我创建时自动生成
class File : public OpenFile
?
更新:我尝试使用指针:
#include <fstream>
#include <memory>
class OpenFile {
public:
};
class File : public OpenFile
{
public:
std::unique_ptr<std::ofstream> file;
};
int main()
{
std::shared_ptr<OpenFile> file;
auto f = std::dynamic_pointer_cast<File>(file);
return 0;
}
但我明白了
/usr/include/c++/6/bits/shared_ptr.h: In instantiation of ‘std::shared_ptr<_Tp1> std::dynamic_pointer_cast(const std::shared_ptr<_Tp2>&) [with _Tp = File; _Tp1 = OpenFile]’:
<span class="error_line" onclick="ide.gotoLine('main.cpp',26)">main.cpp:26:50</span>: required from here
/usr/include/c++/6/bits/shared_ptr.h:458:22: error: cannot dynamic_cast ‘(& __r)->std::shared_ptr::.std::__shared_ptr<_Tp, _Lp>::get()’ (of type ‘class OpenFile*’) to type ‘class File*’ (source type is not polymorphic)
if (_Tp* __p = dynamic_cast<_Tp*>(__r.get()))
解决方案
推荐阅读
- angular - 您可以使用 Angular app.component 将应用程序设置写入本地存储吗?
- javascript - 如何使用淘汰赛仅更新下拉列表
- asp.net-mvc - Bootstrap 4不能垂直居中行div
- html - SVG 文本选择在 Chrome 中不起作用吗?
- javascript - 移入阵列时产生无限循环
- xpath - Xpath 选择所有以下兄弟姐妹以及匹配的元素
- css - 使用grails时如何在gsp中对齐部分中的元素
- ssis - SSIS 计划并重新启动包执行
- javascript - 用于跳过元素的 querySelector
- arrays - 更新 AngularFire2 中的嵌套数组