- 论坛徽章:
- 0
|
#include<iostream>
#include<string.h>
using namespace std;
class A
{
private:
char *string;
public:
A();
A( char* _string);
void print()
{
cout<<"####"<<string<<endl;
}
~A();
A operator=(A &other);
};
A A: perator= (A &other)
{
int length;
if(this == &other)
return *this;
length = strlen(other.string);
free(string);
string = (char*)malloc(length + 1);
strcpy(string, other.string);
return *this;
}
A::~A()
{
cout<<"析构函数调用";
}
A::A()
{
string = (char*)malloc(1);
string[0]='\0';
}
A::A( char* _string)
{
int length;
length = strlen(_string);
string= (char*)malloc(length + 1);
strcpy(string, _string);
string[length] = '\0';
}
int main(void)
{
A a1;
A a2("how are you" ;
a1.print();
a2.print();
a1 = a2;
a1.print();
a2.print();
}
运行结果:
####
####how are you
析构函数调用####how are you
####how are you
析构函数调用析构函数调用
ps: 为什么在第一个a2.printf()后就调用一次。。。 |
|