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

一,单向关联: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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值