69,371
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
using namespace std;
class A
{
public://¸úÏÂÃæµÄprivate¶Ôµ÷
A(int v = 8):data( new int (v) ) { }
~A(){delete data;}
A(const A& t);
A operator =(A &t);
friend ostream& operator <<(ostream &os,A& t);
private:
int *data;
};
A::A(const A& t)
{
data=new int();
*data=*(t.data);
}
A A::operator =(A &t)
{
if(this==&t)
return *this;
*data=*(t.data);
return *this;
}
ostream& operator <<(ostream &os,A& t)
{
os<<*(t.data);
return os;
}
class B
{
public://¶Ôµ÷
B(int sz = 100):max(sz), element( new int [max] ) {for(int i=0;i<max;++i) element[i]=0; } //这里改了下
~B(){delete []element;}
B(const B& t);
B operator =(B &t);
friend ostream& operator <<(ostream &os,B& t);
private:
size_t max;
int *element;
};//
B::B(const B& t)
{
element=new int[t.max];
max=t.max;
memcpy(element,t.element,t.max*sizeof(int));
}
B B::operator =(B &t)
{
if(this==&t)
return *this;
if(max<t.max)
{
delete []element;
element=new int[t.max];
}
max=t.max;
memcpy(element,t.element,t.max*sizeof(int));
return *this;
}
ostream& operator <<(ostream &os,B& t)
{
for(int i=0;i<t.max;++i)
os<<t.element[i]<<" ";
return os;
}
int main(void)//测试
{
A a,b(98),c(b);
B ba(5),bb(ba),bc(10);
cout<<"a : "<<a<<endl;
cout<<"b : "<<b<<endl;
cout<<"c : "<< c<<endl;
b=a;
cout<<"b : "<<b<<endl;
cout<<"ba: "<<ba<<endl;
cout<<"bb: "<<bb<<endl;
cout<<"bc: "<<bc<<endl;
bc=ba;
cout<<"bc: "<<bc<<endl;
system("pause");
return 0;
}