2013-02-11 29 views
0

如何在兩個對象(雙向鏈接的子對象和父對象)中正確引用子對象和父對象?當這樣做,我得到一個編譯錯誤:**** does not name a type。由於#define標籤,我懷疑它與#include語句被忽略。這些標籤應該如何包含在內?如何在這兩個類中雙重引用子類和父類

的三個文件(Parent.h,Child.h,main.cpp中)寫爲這樣:

/* Parent.h */ 
#pragma once 
#ifndef _CHILD_CLS 
#define _CHILD_CLS 

#include "Child.h" 

class Parent { 
public: 
    Parent() {} 
    ~Parent() {} 
    void do_parent(Child* arg); 
}; 
#endif 

/* Child.h */ 
#pragma once 
#ifndef _CHILD_CLS 
#define _CHILD_CLS 

#include "Parent.h" 

class Child { 
public: 
    Child() {} 
    ~Child() {} 
    void do_child(Parent* arg); 
}; 
#endif 

/* main.cpp */ 
#include "child.h" 
#include "parent.h" 

int main() 
{ 
    Child a(); 
    Parent b(); 
    a.do_parent(Child& arg); 
    return 0; 
} 

回答

1

您定義了兩個函數而不是對象,見most vexing parse

更新

Child a();    // a is a function returns Child object 
Parent b();    // b is a function returns Parent object 
a.do_parent(Child& arg); 

TO

Child a;   // a is a Child object 
Parent b;   // b is a Parent object 
b.do_parent(&a); 

此外,你必須circular include問題,打破圓形包括,您需要轉發一個類型:

兒童.h

#pragma once 
#ifndef _CHILD_CLS 
#define _CHILD_CLS 

//#include "Parent.h" Don't include Parent.h 
class Parent;   // forward declaration 
class Child { 
public: 
    Child() {} 
    ~Child() {} 
    void do_child(Parent* arg); 
}; 
#endif 

Child.cpp

#include "Parent.h" 
// blah 
+0

哎!謝謝。這工作。但是,如果Child的一個實例處於Parent中,是否有任何方式(除了指針)可以訪問此Child實例? – jhtong 2013-02-11 09:20:47

+0

孩子可以是家長的成員,但你仍然需要小心通知包括問題:) – billz 2013-02-11 09:35:08

1

你必須的頭文件的循環依賴關係。只需向前聲明其中一個標題中的任一類即可。例如:

/* Parent.h */ 
#pragma once 
#ifndef _CHILD_CLS 
#define _CHILD_CLS 

//#include "Child.h" ----> Remove it 
class Child;   //Forward declare it 

class Parent { 
public: 
    Parent() {} 
    ~Parent() {} 
    void do_parent(Child* arg); 
}; 
#endif 
+0

謝謝。應該怎麼做,例如在Child標題中聲明#include「Parent.h」,並在Parent標頭中聲明#include「Child.h」? – jhtong 2013-02-11 09:04:59

+0

@toiletfreak:我已經展示瞭如何做到這一點的代碼示例。 – 2013-02-11 09:06:16

+0

我試圖在Parent.h中放置一個#include ,但它仍然給出'不命名類型'的錯誤。 – jhtong 2013-02-11 09:06:19

1

使用類原型/向前聲明:

class Child; 

class Parent; 

每個人的類聲明之前,取下包括。

0

的錯誤,我(你應該總是包括完整未經編輯錯誤消息,要求有關編譯/鏈接錯誤時),是這一行:

a.do_parent(Child& arg); 

你應該通過一個指向這裏的Child對象,而不是變量聲明:

b.do_parent(&a); 
0

你需要有一個向前聲明的class Parentclass Child。嘗試修改其中一個文件。

在你Parent.h:

#pragma once 
#ifndef _CHILD_CLS 
#define _CHILD_CLS 

class Child;  // Forward declaration of class Child 

class Parent { 
public: 
    Parent() {} 
    ~Parent() {} 
    void do_parent(Child* arg); 
}; 
#endif 

或者在您的Child.h:

#pragma once 
#ifndef _CHILD_CLS 
#define _CHILD_CLS 

class Parent; // Forward declaration of class Parent 

class Child { 
public: 
    Child() {} 
    ~Child() {} 
    void do_child(Parent* arg); 
}; 
#endif 

This question應該幫助你很多。