64,653
社区成员
发帖
与我相关
我的任务
分享
//IsEcho.h
#include <iostream>
class IsEcho
{
private:
const int BUFSIZE;
char *pStr;
public:
IsEcho(const char *p = 0);
IsEcho(const IsEcho &);
IsEcho & operator = (const IsEcho &);
virtual ~IsEcho();
void say();
};
//IsEcho.cpp
#include "IsEcho.h"
using namespace std;
IsEcho::IsEcho(const char *p):BUFSIZE(1024)
{
cout << "this is IsEcho()" << endl;
this->pStr = new char[this->BUFSIZE];
strcpy(this->pStr,p);
}
IsEcho::IsEcho(const IsEcho& is):BUFSIZE(1024)
{
cout << "this is IsEcho(IsEcho &)" << endl;
this->pStr = new char[this->BUFSIZE];
strcpy(this->pStr,is.pStr);
}
IsEcho::~IsEcho()
{
cout << "this is ~IsEcho()" << endl;
delete this->pStr;
}
IsEcho& IsEcho::operator =(const IsEcho& is)
{
cout << "this is operator = " << endl;
this->pStr = new char[this->BUFSIZE];
strcpy(this->pStr,is.pStr);
return *this;
}
void IsEcho::say()
{
cout << this->pStr << endl;
}
#include "IsEcho.h"
using namespace std;
int main()
{
{
IsEcho is1("test");
is1.say();
IsEcho is2(is1);
is2.say();
IsEcho is3 = is2;
is3.say();
}
system("pause");
return 0;
}
IsEcho is3;
is3=is2;
#include "IsEcho.h"
using namespace std;
int main()
{
{
IsEcho is1("test");
is1.say();
IsEcho is2(is1);
is2.say();
IsEcho is3 = is2; // 这样是构造一个对象,不需要用到赋值,编译器帮你简化了
is3.say();
}
system("pause");
return 0;
}
#include "IsEcho.h"
using namespace std;
int main()
{
{
IsEcho is1("test");
is1.say();
IsEcho is2(is1);
is2.say();
IsEcho is3;
is3 = is2; // 这样会进赋值
is3.say();
}
system("pause");
return 0;
}
IsEcho& IsEcho::operator =(const IsEcho& is)
{
cout << "this is operator = " << endl;
if (*this == is) {
return *this;
}
this->pStr = new char[this->BUFSIZE];
strcpy(this->pStr,is.pStr);
return *this;
}