- #include<iostream>
- using namespace std;
- class myclass{
- public:
- int *p;
- int a;
- myclass(int *fp,int x){
- cout<<" constructor "<<endl;
- a=x;
- p=fp;
- }
- myclass(const myclass &b){
- cout<<" copy-struct"<<endl;
- a=2*b.a;
- system("pause");
- }
- ~myclass(){
- cout<<" destruct"<<endl;
- }
- };
- myclass f(myclass y)//myclass y(t)
- {
- cout<<"-------------in f(y)--------------------"<<endl;
- cout<<"&y="<<&y<<endl;
- cout<<" y.a++="<<y.a++<<"/n"<<endl;
- return y;//copy-construct
- }
- myclass addf(myclass &y)//myclass &y=t;
- {
- cout<<"-------------in addf(&y)----------------"<<endl;
- cout<<"&Y: "<<&y<<endl;
- cout<<" y.a++="<<y.a++<<"/n"<<endl;
- return y;//copy-construct
- }
- int main()
- {
- int x=0;
- myclass t(&x,2);
- cout<<"after creat t(2)"<<endl;
- cout<<"&t="<<&t<<endl;
- cout<<"f(t).a= "<<f(t).a<<endl;
- cout<<"AFTER F(T), NEXT IS ADDF(&T)"<<endl;
- cout<<"right know/n t(2)="<<t.a<<"/n"<<endl;
- cout<<"addf(&t).a= "<<addf(t).a<<endl;
- cout <<"before end of main"<<" t(2)="<<t.a<<endl;
- system("pause");
- }
构造函数,用来给类赋初值,还有一种特殊的构造函数,叫拷贝构造函数,进行对象初始化,当对象以值传递方式掉入函数f(myclass),或者以值传递方式返回 如return myclass,都会调用拷贝构造函数,如上程序,拷贝构造函数使原对象乘2,这样在调用和返回时会使对象各乘2,但是如果没有显示定义拷贝构造函数那么在调用时编译器会默认一个为拷贝,实际上在传入和返回时都开辟了空间,通过拷贝构造函数开辟空间。
资料:http://zhidao.baidu.com/question/7513262.html
函数结果:图片