首页 > 解决方案 > 简单的 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()))

标签: c++

解决方案


推荐阅读