康康代码:
#include <iostream>
#include <cstring>
using namespace std;
class Test
{
private:
int a;
char *str;
public:
Test(int b,char *s)
{
a=b;
str=new char[strlen(s)+1];
strcpy(str,s);
}
void setA(int b) {a=b;}
void setStr(char *s) {strcpy(str,s);}
void show() {cout<<a<<","<<str<<endl;}
Test(const Test&C)
{
a=C.a;
str=new char[strlen(C.str)+1];
strcpy(str,C.str);
}
~Test()
{
delete str;
cout<<"xigouhanshu"<<endl;
}
};
int main()
{
Test xx(100,"hello");
Test yy(xx);
xx.show(); yy.show();
xx.setA(80); xx.setStr("abc");
xx.show(); yy.show();
}
运行结果为:
100,hello
100,hello
80,abc
100,hello
xigouhanshu
xigouhanshu
函数执行顺序:
再看一个代码:
#include <iostream>
#include <cstring>
using namespace std;
class Test
{
private:
int a;
char *str;
public:
Test(int b,char *s)
{
a=b;
str=new char[strlen(s)+1];
strcpy(str,s);
}
void setA(int b) {a=b;}
void setStr(char *s) {strcpy(str,s);}
int getA( ) {return a; }
void show() {cout<<a<<","<<str<<endl;}
Test(const Test&C)
{
a=C.a;
str=new char[strlen(C.str)+1];
strcpy(str,C.str);
}
~Test()
{
delete str;
cout<<"xigouhanshu"<<endl;
}
};
Test a(100,"hello");
void f(char xx[])
{
cout<<"function f:"<<endl;
Test x(90,xx);
static Test y(0,"static");
x.show( ); y.show( );
y.setA(y.getA( )+10);
}
int main()
{
Test b(a);
a.show(); b.show();
b.setA(80); b.setStr("abc");
a.show(); b.show();
f("111");f("222");f("333");
}
运行结果为:
100,hello
100,hello
100,hello
80,abc
function f:
90,111
0,static
xigouhanshu
function f:
90,222
10,static
xigouhanshu
function f:
90,333
20,static
xigouhanshu
xigouhanshu
xigouhanshu
xigouhanshu
静态(static)局部变量在调用结束时并不释放,在main函数结束后才会调用析构函数
最后三个输出的xigouhanshu一个是静态对象的析构函数一个是Test a一个是Test b的析构函数