简体   繁体   English

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

[英]C++ Accessing class members from another class

I have 2 objects in my code (object 'A' and object 'B'). 我的代码中有2个对象(对象“ A”和对象“ B”)。 Firstly, in my main function I create the 'A' object, then inside the 'A' object, I create the 'B' object. 首先,在我的主要功能中,创建“ A”对象,然后在“ A”对象中,创建“ B”对象。 Now I want to be able to call some functions and access some class members of one of the classes from the other class. 现在,我希望能够调用某些函数并从另一个类访问其中一个类的某些类成员。 It's easy to access 'B' members from 'A' but I can't do the opposite. 从“ A”访问“ B”成员很容易,但我不能相反。

In brief: - From 'A' I want to access some 'B' class members. 简而言之:-我想从“ A”访问一些“ B”类成员。 - From 'B' I want to access some 'A' class members. -我想从“ B”访问一些“ A”类成员。

My code (this is just a little example to try to explain what I want to do.): 我的代码(这只是一个小例子,试图解释我想要做什么。):

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 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 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();
}

ah

#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

bh 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

When I try to compile I get this error: "error: invalid use of incomplete type 'class a'". 当我尝试编译时,出现以下错误:“错误:不完整类型'class a'的无效使用”。 And then: "error: forward declaration of 'class a'". 然后:“错误:'a类'的前向声明”。

I guess there's something wrong with forward declaration but I read I had to use it to avoid circular reference in header files. 我猜前向声明有问题,但我读到必须使用它以避免头文件中的循环引用。

Any help or suggestion would be really appreciated. 任何帮助或建议,将不胜感激。 Thanks in advance. 提前致谢。

In your ah, do another forward declaration for class b. 在你的ah中,为b类做另一个前向声明。 It's called as circular forward declaration. 这称为循环前向声明。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM