#include"aa.h"
#include<iostream.h>
#include<stdio.h>
#include<string.h>
class bb
{
public:
char *i;
bb ()
{this->i=0;
cout<<("no pram!\n");
}
bb (bb &b)//
{this->i=new char[10];
strcpy(this->i,b.i);
cout<<("深度复制!\n");
}
bb (char *i)//深度复制
{this->i=new char[10];
strcpy(this->i,i);
cout<<("with pram!\n");
}
~bb()//析构函数
{
if(0!=this->i)
delete this->i;
cout<<("destry!\n");
}
bb & operator=(bb &b)//对于要不要反悔值,是看如果在main中a=a1,就不要返回会也可以,如果是这样的a=a1=a2,就则就
定要反回值
{
this->i=new char[10];
strcpy(this->i,b.i);
return *this;
}
};
void operator<<(ostream &b1,bb &b2)
{
b1<<b2.i<<endl;
}
int main()
{
bb a("tom"),a1;
a1=a;
bb a2=a1;
cout<<a;
return 0;
}
在c++中怎么输出类中成员
cout<<a<<endl;则也会出错,为什么呢
下面是原因
#include"aa.h"
#include<iostream.h>#include<stdio.h>
#include<string.h>
class bb
{
public:
char *i;
bb ()
{this->i=0;
cout<<("no pram!\n");
}
bb (bb &b)//
{this->i=new char[10];
strcpy(this->i,b.i);
cout<<("深度复制!\n");
}
bb (char *i)//深度复制
{this->i=new char[10];
strcpy(this->i,i);
cout<<("with pram!\n");
}
~bb()//析构函数
{
if(0!=this->i)
delete this->i;
cout<<("destry!\n");
}
bb & operator=(bb &b)//对于要不要反悔值,是看如果在main中a=a1,就不要返回会也可以,如果是这样的a=a1=a2,就则就定要反回值
{
this->i=new char[10];
strcpy(this->i,b.i);
return *this;
}
};
ostream & operator<<(ostream &b1,bb &b2)//为什么有全局函数,是因为在cout的重载里只有对(1,2,4,8)有重载,所以我 们不能在类成员重载
{
b1<<b2.i<<endl;
return b1;
}
int main()
{
bb a("tom"),a1;
a1=a;
bb a2=a1;
cout<<a;
//其实是在这样远行的
::operator<<(cout,a).operator<<(endl);
return 0;
}