程序如下:
#include<iostream.h>
class A
{
int i;
public:
A(){i=0;cout<<"Default Called!\n";}
A(int x){i=x;cout<<"Constructor Called!\n";}
A(A & t){i=t.i;cout<<"Copy-constructor Called!\n";}
~A(){cout<<"Destructor Called!\n";}
A & operator = (A & t){i=t.i;cout<<"Operator= Called!\n";return *this;}
void display(void){cout<<"$$$$$$$$$$$$$$$\n";cout<<i<<endl;}
};
A fun(A & t, int i)
{
if(i==0)return t;
cout<<endl;
fun(t,--i); //注意,这里没用return;
}
void main()
{
A a(5),b;
int i=3;
cout<<"@@@@@@@@@@@@@@@@\n";
b=fun(a,i);
b.display ();
cout<<"***************\n";
cout<<"End!\n";
}
以下是运行结果:
/*
Constructor Called!
Default Called!
@@@@@@@@@@@@@@@@
Copy-constructor Called!
//出现三个析构函数?????(为什么没有相应的构造函数??)
Destructor Called!
Destructor Called!
Destructor Called!
Operator= Called!
Destructor Called!
$$$$$$$$$$$$$$$
4350224 //结果不正确,若在fun()中添加return就可以得到正确结果,但同样的用法在下面的程序中却能得到正确结果!
***************
End!
Destructor Called!
Destructor Called!
Press any key to continue*/
******************************
类似用法,但参数类型为 int
#include<iostream.h>
int fun(int n)
{
if(n==1)
return n;
fun(n-1);
}
void main()
{
int b;
b=fun(5); //同样没有return!
cout<<b<<endl;
}
结果::
/*
1
Press any key to continue*/
[此贴子已经被作者于2007-5-30 18:10:20编辑过]