【发布时间】:2015-08-17 15:27:26
【问题描述】:
我一直在头文件中进行前向声明,并在 cpp.xml 中包含实际的类文件。但是当类被模板化时我遇到了问题:
class MyClass {
public:
MyClass();
void aFunction();
private:
QList<int> m_member;
};
要构建它,我需要提供有关 QList 的此类信息。我试过了:
class QList;
error: template argument required for 'class QList'
我试过了(因为我只需要 QList 这个特定类中的整数):
class QList<int>;
error: specialization of 'QList<int>' after instantiation
我已经查看了这些错误,但只发现了人们在创建类模板时遇到的问题,没有发现任何关于前向声明的问题。
如果没有其他方法,我可以在头文件中 #include <QList> 并放弃前向声明 - 但我想了解这个问题。
关于template classes forward declarations的最热门问题也建议使用此选项:
只需
#include <list>,别担心。
我不明白other answers...
【问题讨论】:
-
如果你想让
QList<int>作为你的类的成员,无论如何都需要完整的声明(因为编译器需要计算你的类的大小)。使用前向声明,您可以拥有指针或引用,但仅此而已。 -
@BoPersson 如果列表的大小未知,它怎么能做到这一点?
-
QList<int>对象将始终具有相同的大小。列表中的ints会单独分配。 -
你引用的编译器错误听起来像
<QList>,实际上已经包含在内,所以再次包含它不会有什么坏处。
标签: c++ templates forward-declaration