如何在C ++中使用std :: unique_ptr?

问题描述 投票:0回答:1

我想做的是使用std :: unique_ptr函数来打开三种不同类型的Reader文件(.rdr,.rrd,.drr),所有这些文件都具有基类Reader。基本类以及三个阅读器类如下:

class Reader
{
protected:
  vector<Read> _reads;
}

class Reader1 : public Reader
{
private:
  int num;
};
class Reader2 : public Reader 
{
private:
  int num;
};
class Reader3 : public Reader
{
private:
  int num;
};

我需要帮助的是实现以下功能

static std::unique_ptr<Reader> create(const QString& file) {
// code here
}

这是我到目前为止的尝试:

static std::unique_ptr<Reader> create(const QString& file)
{
    return std::unique_ptr<Reader> (create(file)); // gives the error 'all paths through this function will call itself'
}

这就是我调用该函数的方式:

  if (tmp == "rdr") {
    file = createTempFile();

    auto readerfile = Reader::create(fileName);

我想我不太了解unique_ptr函数是如何工作的,这可能就是为什么我在实现unique_ptr函数时遇到问题。非常感谢您的任何帮助,谢谢!

c++ class inheritance static-methods
1个回答
0
投票

您对create()的实现应类似于

static std::unique_ptr<Reader> create(const QString& file) {
    if (file == "<string for Reader1>")
       return std::make_unique<Reader1>(...);
    ...
}
© www.soinside.com 2019 - 2024. All rights reserved.