【发布时间】:2022-01-21 21:44:36
【问题描述】:
我写了一个简单的智能点类,但遇到了麻烦。 A 类中的代码BPtr mBptr; 在编译时运行良好,但在其他一些类中失败并出现错误:“错误 C2027:使用未定义类型”。所以我必须在头文件中包含 B.h 而不是使用前向声明。我不知道发生了什么。有人知道吗?
我这样写了这些代码:
//Pointer.h
template<class T>
class Pointer
{
public:
Pointer(T* pObject = nullptr);
...
private:
T* mPtr;
};
//Pointer.inl
template <class T>
Pointer<T>::Pointer(T* pObject)
{
mPtr = pObject;
if (mPtr)
{
mPtr->IncreRef();//IncreRef: function of class T
}
}
...
而我是这样使用的:
//A.h
#include "Pointer.h"
class B;
typedef Pointer<B> BPtr;
class A
{
public:
A();
~A();
private:
BPtr mBptr; //This might compiler error c2027
};
//A.cpp
#include "A.h"
#include "B.h"
A::A()
{
}
A::~A()
{
}
【问题讨论】:
-
你在哪里
#include "Pointer.inl"? (仅供参考:SO: Why can templates only be implemented in the header file?) -
“但在其他一些类中失败并出现错误:“错误 C2027:使用未定义的类型”。“ - 产生该特定条件的正确 minimal reproducible example对我们来说是你的帖子应该包含的内容。
标签: c++ templates forward-declaration