C++ - shared_ptr "Unspecialised class template"错误

C++ - "Unspecialised class template" error with shared_ptr

本文关键字:Unspecialised class template 错误 ptr shared C++      更新时间:2023-10-16

我有一个类Room,它保存了一个到Option对象的shared_ptrs向量,比如:

private:
vector<shared_ptr<Option> > options;

但由于某些原因,当我构建时,我会出现以下错误:

  • "shared_ptr":非专用类模板不能用作模板参数"_Ty"的模板参数,应为实类型
  • "std::tr1::shared_ptr":使用类模板需要模板参数列表

奇怪的是,我还有一个shared_ptrs向量,语法完全相同,但这个向量没有问题。

还有很多地方会出现错误"Option':未声明的标识符",这让我觉得Option类可能有问题,但似乎没问题。这是选项的代码:

选项.h:

#pragma once
#include "Room.h"
#include <memory>
using namespace std;
class Option
{
protected:
    int id;
    char* text;
public:
    Option(void);
    Option(int, char*);
    virtual ~Option(void);
    char* getText();
    int getID();
};

Option.cpp:

#include "Option.h"
#include "Room.h"
#include <memory>
using namespace std;
Option::Option(void)
{
}
Option::Option(int newID, char* newText){
    id = newID;
    text = newText;
}
Option::~Option(void)
{
}
char* Option::getText(){
    return text;
}
int Option::getID(){
    return id;
}

由于您还没有发布Room类的代码,因此这个答案中有一些猜测。我假设这个代码是

private:
vector<shared_ptr<Option> > options;

位于Room.h中。您的Option.h文件包括Room.h,因此Room类在Option类之前声明。因此,当编译Room类的析构函数并且shared_ptr实现试图删除Option对象时,Option是一个不完整的类型。

从上面的代码中,我不明白为什么Option.h需要包括Room.h.事实上,它应该是相反的。如果它确实需要包含该文件,您应该能够通过在Room.cpp.中显式声明Room::~Room()来解决这个问题

编辑:
事实证明~shared_ptr<T>并不要求T是一个完整的类型。然而,shared_ptr<T>( T* )shared_ptr<T>::reset( T* )确实如此,问题可能是因为vector上的某些操作正在调用其中一个(更可能是前者)的调用。

vector<shared_ptr<Option >>

你几乎做对了:)

vector<shared_ptr<Option> >

这两个>字符在触摸时会导致您看到的奇怪错误。它被解释为>>运算符。

顺便说一句,感谢您按照原样发布代码,而不是重新输入并可能隐藏错误。