gpt4 book ai didi

C++ 从另一个类访问类成员

转载 作者:太空宇宙 更新时间:2023-11-04 13:51:17 24 4
gpt4 key购买 nike

我的代码中有 2 个对象(对象“A”和对象“B”)。首先,在我的主要功能中,我创建了“A”对象,然后在“A”对象中,我创建了“B”对象。现在我希望能够调用一些函数并从另一个类访问其中一个类的一些类成员。从“A”访问“B”成员很容易,但我不能做相反的事情。

简而言之:- 我想从“A”访问一些“B”类成员。- 我想从“B”访问一些“A”类成员。

我的代码(这只是一个小例子,试图解释我想做什么。):

mian.cpp

#include <iostream>
#include "a.h"

using namespace std;

int main()
{
a *pa;

pa=new a();

cout << "Bye" << endl;

delete pa;

return 0;
}

a.cpp

#include <iostream>
#include "a.h"

a::a(void)
{
std::cout << "Class A" << std::endl;
b_a=new b();

b_a->fun1(this);
}

void a::fun2(void)
{
std::cout << "Function 2" << std::endl;
delete b_a;
}

b.cpp

#include <iostream>
#include "b.h"

b::b(void)
{
std::cout << "Class B" << std::endl;
}

void b::fun1(a *pa)
{
std::cout << "Function 1" << std::endl;
a_b=pa;
a_b->fun2();
}

啊.h

#ifndef A_H_INCLUDED
#define A_H_INCLUDED

#include "b.h"

class a
{
private:
b *b_a;

public:
a();
void fun2();

};

#endif // A_H_INCLUDED

b.h

#ifndef B_H_INCLUDED
#define B_H_INCLUDED

class a; // Forward declaration

class b
{
private:
a *a_b;

public:
b();
void fun1(a *pa);
};

#endif // B_H_INCLUDED

当我尝试编译时出现此错误:“错误:无效使用不完整类型‘class a’”。然后:“错误:‘a 类’的前向声明”。

我猜前向声明有问题,但我读到我必须使用它来避免头文件中的循环引用。

如有任何帮助或建议,我们将不胜感激。提前致谢。

最佳答案

在你的 a.h 中,为类 b 做另一个前向声明。它被称为循环前向声明。

http://fw-geekycoder.blogspot.com/2012/04/how-to-resolve-circular-dependencies-in.html

关于C++ 从另一个类访问类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23283043/

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