简单的C ++向下转换不适用于简单的类

时间:2019-11-22 21:07:31

标签: 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()))

0 个答案:

没有答案
相关问题