gpt4 book ai didi

C++ 类相互使用

转载 作者:太空狗 更新时间:2023-10-29 23:52:16 25 4
gpt4 key购买 nike

我有两个类,比如说 A 类和 B 类。我的目标是让两个类都使用彼此的函数。问题是,多文件包含结构似乎不允许我这样做。这是我正在尝试做的事情:

#file A.h

Class A{
public:
int GetInfo();

private:
B * ptrToB;
};

#file B.h

Class B{
public:
int getStuff();
private:
A * ptrToA;
};

我的目标是让 A 类方法能够调用 ptrToB->getStuff(),让 B 类方法能够调用 ptrToA->getInfo()

这可能吗?为何如此?如果不是,为什么不呢?

最佳答案

也许使用前向声明?

#file A.h

#ifndef ACLASS_H
#define ACLASS_H

Class B;

Class A{
public:
int GetInfo();

private:
B * ptrToB;
};

#endif

然后在CPP文件中。

#file A.cpp

#include "B.h"

A::A() : ptrToB(0)
{
// Somehow get B
}

int A::GetInfo()
{
// Return whatever you need in here.
}

对于 B 类 H 和 CPP 文件也会做同样的事情。

前向定义允许编译器识别类型而不需要显式定义。如果您在 A 类中引用了 B,则必须包含 B 的 header 。

由于您使用指针访问 B,编译器不需要知道内部数据,直到您访问它(在 CPP 文件内)。

// Would need the header because we must know 
// the size of B at compile time.
class B;
class A
{
B theB;
}


// Only need forward declaration because a
// pointers size is always known by the compiler
class B;
class A
{
B * bPointer;
}

关于C++ 类相互使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16573629/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com