簡體   English   中英

我如何在c ++中稍后轉發類的聲明並使用其成員函數?

[英]How can I forward declare a class and use its member funcions later in c++?

是否可以向前聲明一個類,然后使用其成員函數? 我正在嘗試這樣做:

class Second;

class First{
private:
  int x=0;
public:
  void move(Second* s,int i){
   s->setLine(i);
   s->called(true);
  }
  int getX(){return x;}
}

class Second{
private:
 int line=2;
 bool cal=false;
public:
 void setLine(int l){line = l;}
 void called(bool b){cal=b}
 bool interact(First* f){
  if ((f->getX())>3)
     return true;
  else
     return false;
 }
}

我的實際問題稍微復雜一點,並且函子可以做更多的事情,但是我想做的是讓這兩個類互相使用函子並以這種方式進行交互。 有誰知道有沒有辦法做到這一點?

是否可以向前聲明一個類,然后使用其成員函數?

不它不是。 在定義該類之前,您不能訪問前向聲明的類,變量,函數,枚舉,嵌套類型等的任何成員。

在定義了前向聲明的類之后,您需要移動調用前向聲明的類的成員函數的函數的實現。

class Second;

class First{
   private:
      int x=0;
   public:
      void move(Second* s,int i); // Don't define it here.
      int getX(){return x;}
};

class Second{

   ...

};

// Define the function now.
void First::move(Second* s,int i){
   s->setLine(i);
   s->called(true);
}

您可以將First::move的定義放在類的Second定義之后。 僅聲明需要出現在First的定義內。

實際上,您可以將First::move的定義放在.cpp文件中,而不要放在任何標頭中。

以下內容將為您解決問題,但最好將聲明和實現分開。

class Second;

class First{
private:
  int x=0;
public:
  void move(Second* s,int i); //<- move implementation after Second's declaration
  int getX(){return x;}
}

class Second{
private:
 int line=2;
 bool cal=false;
public:
 void setLine(int l){line = l;}
 void called(bool b){cal=b}
 bool interact(First* f){
  if ((f->getX())>3)
     return true;
  else
     return false;
 }
};

void First::move(Second* s,int i){
s->setLine(i);
s->called(true);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM