簡體   English   中英

C ++將結構從一類傳遞到另一類

[英]C++ pass struct from from one class to another class

我分別在Ah,A.cpp和Bh,B.cpp中定義了兩個類A和B。 類A具有要在類B的函數中使用的結構。由於類B包含在類A中,因此我不能在類B中包含類A,因為這會導致循環依賴。 下面給出了所有文件的代碼:

#ifndef _A_H
#define _A_H
#include B.h
namespace common {
    class A {
    public:
        static struct strctOfA {
           float p1 = 2;
        } structA;
        void functionOfA();
    };
}
#endif // !_A_H

丙型肝炎

#include A.h
using namespace common;
A::functionOfA() {
    B b;
    b.functionOfB(structA);
}

h

#ifndef _B_H
#define _B_H
namespace common {
    class B {
    public:
         functionOfB(??);
    };
}
#endif // !_B_H

丙型肝炎

#include B.h
using namespace common;
B::functionOfB(??) {
        // Want to use structA here;        
}

我調查了StackOverflow,發現一個線程非常接近我的問題,但是,他們要么無法解釋答案,要么我無法理解他們的解決方案。 請幫我解決一下這個。

謝謝

更新感謝IV指出錯誤並提供了解釋。 更新代碼對我有用。 感謝每個人都為我的C / C ++編碼技能提供了更多知識。 :)

解決方法很簡單,您寫的是一個壞習慣。

沒有理由在Ah中包含Bh,因為您沒有在Ah文件中使用Bh的任何部分。 一種更好的實現方法是在A.cpp中而不是在頭文件中包含Bh。

它還將解決包含問題的循環。

通常,如果您不在頭文件中使用包含文件的功能/對象,建議將文件包括在.cpp文件中,而不是包含在頭文件中:)

此外,對於Windows,您應該一次使用#pragma,對於其他任何情況都應使用#n

#ifndef _A_H
#define _A_H
namespace common {
    class A {
    public:
        static struct strctOfA {
           float p1 = 2;
        } structA;
    }
}
#endif

丙型肝炎

#include A.h
#include B.h
using namespace common;
class A {
    B b;
    b.functionOfB(structA);
}

注意:從B.cpp包括Ah

可以使用前向聲明來完成,除非您絕對必須按值傳遞它。 但是我無法想到這種情況下無法使用引用。

#ifndef A_H_
#define A_H_

struct B;
struct A {void f(B&);};

#endif

丙型肝炎

#include "B.h"
void A::f(B & value) {/* do something */ };

h

#ifndef B_H_
#define B_H_


struct A;
struct B {void f(B&);};

#endif

丙型肝炎

#include "A.h"
void B::f(A & value) {/* do something */ };

如果只需要前向聲明就需要A中的B值,則可以將其放在指針中,即使用std :: unique_ptr。

暫無
暫無

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

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