【问题标题】:Forward declaration class proplem前向声明类问题
【发布时间】: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()
{
}

【问题讨论】:

标签: c++ templates forward-declaration


【解决方案1】:

BPtr mBptr 创建一个对象。

由于Pointer 的构造函数调用B 的方法,B 需要在mBptr 被声明时完全定义。

【讨论】:

  • 我知道我必须在头文件中包含 B.h,但是当我使用前向声明“B 类”时,我的示例代码中没有错误,怎么可能。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多