单向关联、双向关联代码实现

  • Post author:
  • Post category:其他

一,单向关联:A的成员变量里包含B对象

代码实现如:Base和Related

二,双向关联:A,B成员变量互相包含对方对象

代码实现分两种:
1,A和B的对象都是独立的,分别把实例给到A和B,就如两个单向关联,相互独立。
2,A实例一个对象指针,给到B的成员变量A*a,然后通过A的方法把B的this指针给到A的成员变量B*b,这样A和B完全关联,可用互相访问和改变对方的内容。如下实例:Attach和Base

代码实现

#include <iostream>

using namespace std;

class Attach;
class Base;
class Attach
{
public:
    Attach()
    {
        cout<<"this is Attach Construct"<<endl;
    }
    ~Attach()
    {
        cout<<"this is Attach Destruct"<<endl;
    }
    void attchInterface(Base *base)
    {
        mBase = base;
    }
public:
    Base* mBase;     
};

class Base
{
public:
    Base(int value)
    {
        mValue = value;
        cout<<"this is Base Construct"<<endl;
    }
    Base(Attach* attchclient)
    {
        mAttchClient = attchclient;
        cout<<"this is Base Construct"<<endl;
    }
    ~Base()
    {
        cout<<"this is Base Destruct"<<endl;
    }

    void printValue()
    {
        cout<<"mValue = "<<mValue<<endl;
    }
    
    void setValue(int value)
    {
        mValue = value;
    }
#if 1    
    void attach()
    {
        mAttchClient->attchInterface(this);
    }
#endif
public:
    int mValue;
    Attach* mAttchClient;
};

class Related
{
public:
    Related()
    {
        cout<<"this is Related Construct"<<endl;
    }
    ~Related()
    {
        cout<<"this is Related Destruct"<<endl;
    }

public:
    Base* mBase;    
};



int main()
{
    cout<<"--------------------------------------------->"<<endl;
    Base* base = new Base(1);
    base->printValue();
    
    Related re;
    re.mBase = base;
    re.mBase->printValue();
    
    re.mBase->setValue(2);
    re.mBase->printValue();
    base->printValue();
    
    base->setValue(3);
    re.mBase->printValue();
    base->printValue();
    cout<<"<---------------------------------------------"<<endl;
    Attach* attach = new Attach();
    Base* baseattach = new Base(attach);
    baseattach->attach();
    attach->mBase->setValue(4);
    attach->mBase->printValue();
    cout<<"<---------------------------------------------"<<endl;
    return 0;
}


版权声明:本文为weixin_41786823原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。