类间通信实例:
#include<iostream>
using namespace std;
class A{
private:int x;
public:
A(int x)
{
this->x=x;
}
void fun()
{
cout<<"A out"<<endl;
}
~A()
{
cout<<"A Delete"<<endl;
}
};
class B{
private: A *pa;
public:
B(A *t)
{
pa=t;
}
void dofun()
{
pa->fun();
}
~B()
{
cout<<"B Delete"<<endl;
}
};
//①
int main(void)
{
A objA(1);
B objB(&objA);
objB.dofun();
return 0;
}
//②
int main(void)
{
A objA(1);
B *pB=new B(&objA);
pB->dofun();
delete pB;
return 0;
}
//③
int main(void)
{
A *pA=new A(1);
B *pB=new B(pA);
pB->dofun();
delete pA;
delete pB;
return 0;
}
//④
~B()
{
cout<<"B Delete"<<endl;
delete pa;
}
int main(void)
{
B *pB=new B(new A(1));
pB->dofun();
delete pB;
return 0;
}
//⑤
class B{
private: A *pa;
public:
B(int x)
{
pa=new A(x);
}
void dofun()
{
pa->fun();
}
~B()
{
cout<<"B Delete"<<endl;
delete pa;
}
};
int main(void)
{
B *pB=new B(1);
pB->dofun();
delete pB;
return 0;
}
例1:
①
#include<iostream>
using namespace std;
class A{
private:int x;
public:
A()
{
this->x=0;
}
A(int x)
{
this->x=x;
}
void fun()
{
cout<<"x="<<x<<endl;
}
};
class B{
private:int y;
public:
B()
{
this->y=0;
}
B(int y)
{
this->y=y;
}
void fun()
{
cout<<"y="<<y<<endl;
}
};
class C{
private:int z;
public:
C()
{
this->z=0;
}
C(int z)
{
this->z=z;
}
void fun()
{
cout<<"z="<<z<<endl;
}
};
class My{
private:
A *a;
B *b;
C *c;
public:
My(A *ta,B *tb,C *tc)
{
a=ta;
b=tb;
c=tc;
}
void dofun()
{
a->fun();
b->fun();
c->fun();
}
};
int main(void)
{
A *pa=new A(3);
B *pb=new B(4);
C *pc=new C(5);
My *pmy=new My(pa,pb,pc);
pmy->dofun();
//释放(new 出来的对象要用delete释放)
delete pa;
delete pb;
delete pc;
delete pmy;
return 0;
}
②通过析构函数来释放
~My()
{
delete a;
delete b;
delete c;
}
client:
A *pa=new A(3);
B *pb=new B(4);
C *pc=new C(5);
My *pmy=new My(pa,pb,pc);
pmy->dofun();
//释放
delete pmy;
return 0;
③A,B,C的指针直接new出来,必须用方式②来释放
My *pmy=new My(new A(3),new B(4),new C(5));
pmy->dofun();
delete pmy;
return 0;
例2:如图实现,类图,如右图链式输出
#include<iostream>
using namespace std;
class A{
private:int data;
A *next;
public:
A()
{
this->data=0;
next=NULL;
}
A(int data)
{
this->data=data;
next=NULL;
}
void setNext(A *t)
{
next=t;
}
void print()
{
cout<<this->data<<endl;
if(next)
next->print();
}
~A()
{
delete next;
}
};
int main(void)
{
int x;
A *p,*h=NULL;
//建链
for(int i=0;i<3;i++)
{
cout<<"输入数据"<<endl;
cin>>x;
p=new A(x);
p->setNext(h);//注意next为私有,不可直接调用
h=p;
}
h->print();
delete h;
return 0;
}