c ++纯虚拟类的前向声明

时间:2010-07-09 11:11:11

标签: c++ class pure-virtual

我有前向减速问题。我之前有一个普通的类,名为GlobalCWND,它被实例化并在另一个类ProtocolContext中使用。

我在Requestor.h中声明了ProtocolContext类。

您可以看到这两个类的代码的相关部分。

============协议背景========

 class Requestor<RequestorStrategy>;
 class Receiver<ReceiverStrategy>;

 class ProtocolContext : public Object
 {
 public:
   ProtocolContext(Ptr<SubscriptionContext> , Ptr<ReceiverStrategy> , Ptr<
       RequestorStrategy> );
.......

 ProtocolContext::ProtocolContext(Ptr<SubscriptionContext> sctx, Ptr<
      ReceiverStrategy> rec, Ptr<RequestorStrategy> req) :
    receiver(rec), requestor(req)
  {
    m_sctx = sctx;
    Ptr<GlobalCWND> m_globalCWND = Create<GlobalCWND> (this);
    cout << "Initializing Protocol Context for rid"
        << m_sctx->GetMetaDataStrategy()->GetRid() << endl;
    m_ph = Create<PacketHandler> (sctx);
  }

================= Requestor.h ======

 class ProtocolContext;

 class RequestorStrategy : public Object
 {

 public:
   RequestorStrategy()
   {
   }
   ;
   ~RequestorStrategy()
   {
   }
   ;
   /* Transitions */
   virtual void
   Trans(Ptr<ProtocolContext> , Ptr<Packet> ) = 0;
 };

.....

以前工作正常。现在我将GlobalCWND更改为虚拟类,在协议上下文构造函数中,我有以下代码:

ProtocolContext::ProtocolContext(Ptr<SubscriptionContext> sctx, Ptr<
      ReceiverStrategy> rec, Ptr<RequestorStrategy> req) :
    receiver(rec), requestor(req)
  {
    m_sctx = sctx;
    Ptr<GlobalCWND> m_globalCWND = Create<GlobalCWNDSimple> (this);

..............
}

但现在我收到了这个错误:

 GlobalCWND.h:21:   instantiated from here
ptr.h:441: error: invalid use of incomplete type ‘struct
ProtocolContext’
Requestor.h:16: error: forward declaration
of ‘struct ProtocolContext’

错误行是:

line 21 of GlobalCWND() is    GlobalCWND (){};
and line 16 of Requestor.h is class ProtocolContext;

Ptr类实际上是创建指向对象的指针,ptr.h的第441行是这个函数的最后一行:

template <typename T>
Ptr<T>::~Ptr ()
{
 if (m_ptr != 0)
   {
     m_ptr->Unref();
   }
}

GlobalCWND的代码如下所示:

 class ProtocolContext;

  class GlobalCWND : public Object
  {
  public:
    GlobalCWND (){};
    GlobalCWND (Ptr<ProtocolContext>){};
    ~GlobalCWND (){};

    static TypeId GetTypeId(){
      static TypeId tid = TypeId("GlobalCWND")
      .SetParent<Object> ()
      ;
      return tid;
    };

1 个答案:

答案 0 :(得分:2)

GlobalCWND的构造函数取值为Ptr<ProtocolContext>,在析构函数中调用ProtocolContext指针上的方法。
但是,根据错误,ProtocolContext在此时尚未完成 - 您需要包含ProtocolContext的声明。
有关不完整类型可以做什么和不可以做什么的列表,请参阅this answer