【问题标题】:C++ Accessing class members from another classC ++从另一个类访问类成员
【发布时间】:2014-04-25 02:10:23
【问题描述】:

我的代码中有 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'”。然后:“错误:'class a'的前向声明”。

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

任何帮助或建议将不胜感激。提前致谢。

【问题讨论】:

    标签: c++ class pointers object member


    【解决方案1】:

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

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

    【讨论】:

    • 感谢您的链接,它成功了。我必须为 b 类做另一个前向声明,并在我的 b.h 中添加 #include "a.h"。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-25
    • 1970-01-01
    相关资源
    最近更新 更多