Communication between objects in C ++

I have two classes A and B, which are defined as follows:

class A
{
    public:
    void *connector;
};

class B
{
    public:
    void *connector1;
    void *connector2;
};

First, suppose I create three objects C1, C2, and C3 based on these classes,

A C1;
B C2;
A C3;

And I use the following code to connect them

C1.connector = &C2;
C2.connector1 = &C1;
C2.connector2 = &C3;
C3.connector = &C2;

So, at the moment I have this: C1 ↔ C2 ↔ C3 (first example).

Important: the reason I use void pointers in all classes is because I cannot predict from the very beginning how the objects will connect. For example, the answer to this question should be valid if I create the fourth object and make these connections (C1 and C2 the same as before):

B C3;    
A C4;

C1.connector = &C2;
C2.connector1 = &C1;
C2.connector2 = &C3;
C3.connector1 = &C2;
C3.connector2 = &C4;
C4.connector = &C3;

which corresponds to this C1 ↔ C2 ↔ C3 ↔ C4 (second example).

. , , , , . , , . , , C2 C1 .

1) , , . , ( , ).

2) , , , , .

. , , , , B , , .

, ,

int get_value(); 

A, B ( ). , C2 C1, C3 C2. , C2 C3 .

, , , . , , C2 C1, C3 C2 (. 2 ).

, , , C2/C3 get_value C1/C2, C2/C3 / , .

, , , , , , . , , - , - .

.

+4
3

, void * - .

inhertiance:

class OBJ 
{
public:  
    virtual string getValue()=0; 
};

class A : public OBJ 
{
public:
    OBJ *connector;
    string getValue();
};

class B : public OBJ
{
public:
    OBJ *connector1;
    OBJ *connector2;
    string getValue();
};

"" OBJ.

C1.connector->getValue(); 
C1.connector->connector2->getValue(); 
+3

, - , :

// create an interface to communicate with
struct connected
{
    virtual ~connected() {} // must have virtual dtor

    virtual int get_value() = 0; // pure virtual functions
};

class A
: public connected // implement the connected interface
{
    int value;

public:
    A(int value = 0): value(value) {}

    // implement the connected interface
    int get_value() override { return value; }

    connected* connector = nullptr;
};

class B
: public connected // implement the connected interface
{
    int value;

public:
    B(int value = 0): value(value) {}

    // implement the connected interface
    int get_value() override { return value; }

    connected* connector1 = nullptr;
    connected* connector2 = nullptr;
};

int main()
{
    A C1;
    B C2;
    A C3;

    C1.connector = &C2;
    C2.connector1 = &C1;
    C2.connector2 = &C3;
    C3.connector = &C2;

    C2.connector1->get_value(); // use the connected interface
}

, A, B connected, , connected, , A B.

+2

I do not know your specific needs, but perhaps you will read the observer pattern , this may help you. Or maybe you can try using it Qt, it has a good siganl-slot mechanism.

+1
source

All Articles