是否可以在不同类之间使用来自类成员的同一实例?

时间:2019-04-12 20:22:16

标签: c++ class

我想使用从B类调用的A类成员, 当我实际上在A内声明B类时,这有意义吗?

在更大的代码中,我正面临这种可能性,我想知道是否有可能,或者我可以使用其他替代方法/

我尝试将A放入B内,但是它正在分发,并且编译器不允许我这样做。 (www onlinegdb com)(使用c ++)

//main.cpp
#include <stdio.h>
#include "a.h"

class A objA;

int main()
{
   A::get_instance().funA();

    return 0;
}
//a.h
#include <stdio.h>
#include "b.h"

class A
{
public:
    // Singleton instance
        static A& get_instance()    //static memory allocation
        {
            static A instance;
            return instance;
        }

    A();
    ~A();
    void funA();
    void funA_two();

   //Member
   B obj_b;
};
//a.cpp
#include "a.h"

A::A()
{ /*do nothing here*/}

A::~A()
{ /*do nothing here*/}

void A::funA()
{
    printf("Hello Class A\r\n");
    obj_b.funB();
}

void A::funA_two()
{
    printf("I want to be called from class B\r\n");
}
//b.h
#include <stdio.h>

class B
{
public:
    // Singleton instance
        static B& get_instance()    //static memory allocation
        {
            static B instance;
            return instance;
        }
    B();
    ~B();
    void funB();    
};
//b.cpp
#include "b.h"
//#include "a.h"

B::B()
{ /*do nothing here*/}

B::~B()
{ /*do nothing here*/}

void B::funB()
{
    printf("Hello Class B\r\n");

    //From here. how can I call the same A instance to call funA_two()?
}

actually, I would like to do some like a function pointer as C, to pass the funA_two to funB

0 个答案:

没有答案