首頁 >後端開發 >C++ >如何建立兩個相互引用的C類?

如何建立兩個相互引用的C類?

Patricia Arquette
Patricia Arquette原創
2024-11-10 08:16:02746瀏覽

How to Create Two C   Classes that Mutually Reference Each Other?

兩個互相引用的類別

建立兩個C 類,每個類別都直接包含另一種類型的物件是不可能的,因為循環引用問題。但是,解決方法涉及使用指標來相互引用。

前向聲明和指標用法

要實現此目的,請在頭文件中使用前向聲明來建立存在另一個類別而不定義它:

// bar.h
class foo; // Say foo exists without defining it.

class bar {
public:
  foo* getFoo();
protected:
  foo* f;
};
// foo.h
class bar; // Say bar exists without defining it.

class foo {
public:
  bar* getBar();
protected:
  bar* f;
};

然後,在各自的.cpp文件,包含其他標頭來完全定義類別:

// bar.cpp
#include "foo.h"

foo* bar::getFoo() { return f; }
// foo.cpp
#include "bar.h"

bar* foo::getBar() { return f; }

這種方法打破了循環引用循環,因為前向聲明允許類別在不包含標頭的情況下承認彼此的存在,防止物件出現無限空間問題。

以上是如何建立兩個相互引用的C類?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn