标签:
函数形参诗引用,程序输出如程序最后的注释,表明引用s代表的是对象s2.
//函数中的引用 #include<iostream> using namespace std; class Sample { int x; public: Sample(int a): x(a) { cout<<"call constructor Sample(int a)"<<endl; } Sample(Sample &a): x(a.x) { cout <<"call constructor Sample(Sample &a)"<<endl; } int getX(){ return x;} }; //形参为引用 void disp(Sample &s) { cout << s.getX();} //void disp(Sample s) { cout << s.getX();} int main() { Sample s1(22), s2(s1); disp(s2); return 0; } /*output call constructor Sample(int a) call constructor Sample(Sample &a) 22 */
函数形参不是引用程序输出如注释,结果显示调用了两次类Sample的复制构造函数,第一次是创建S2对象时调用,第二次是传递参数时调用,即将s1对象拷贝给形参s时调用了复制构造函数。
#include<iostream> using namespace std; class Sample { int x; public: Sample(int a): x(a) { cout<<"call constructor Sample(int a)"<<endl; } Sample(Sample &a): x(a.x) { cout <<"call constructor Sample(Sample &a)"<<endl; } int getX(){ return x;} }; //形参不是引用 //void disp(Sample &s) { cout << s.getX();} void disp(Sample s) { cout << s.getX();} int main() { Sample s1(22), s2(s1); disp(s1); return 0; } /*output call constructor Sample(int a) call constructor Sample(Sample &a) call constructor Sample(Sample &a) 22 */
返回值是非引用对象,返回栈中的对象,函数返回后栈中的对象消失。
#include<iostream> using namespace std; class Sample { int x; public: Sample() {} Sample(int a): x(a) { cout<<"call constructor Sample(int a)"<<endl; } Sample(Sample &a): x(a.x) { cout <<"call constructor Sample(Sample &a)"<<endl; } ~Sample() { cout << "call destructor"<<endl; } int getX(){ return x;} }; //形参是引用 void disp(Sample &s) { cout << s.getX()<<endl;; } //返回值不是引用 Sample copy(Sample &a) { Sample s(a.getX()); cout<<"call copy function"<<endl; return s; } int main() { Sample s1(22), s2; s2 = copy(s1); disp(s2); return 0; } /*output call constructor Sample(int a) call constructor Sample(int a) call copy function call destructor 22 call destructor call destructor */
#include<iostream> using namespace std; class Sample { int x; public: Sample() {} Sample(int a): x(a) { cout<<"call constructor Sample(int a)"<<endl; } Sample(Sample &a): x(a.x) { cout <<"call constructor Sample(Sample &a)"<<endl; } ~Sample() { cout << "call destructor"<<endl; } int getX(){ return x;} }; //形参是引用 void disp(Sample &s) { cout << s.getX()<<endl;; } //返回值是引用 Sample& copy(Sample &a) { //本地变量,程序发出警告,引用本地变量 Sample s(a.getX()); cout<<"call copy function"<<endl; return s; } int main() { Sample s1(22), s2 = copy(s1); //s2 = copy(s1); disp(s2); return 0; } /*output call constructor Sample(int a) call constructor Sample(int a) call copy function call destructor call constructor Sample(Sample &a) 2686744 call destructor call destructor */ int main() { Sample s1(22), s2; s2 = copy(s1); disp(s2); return 0; } /*output call constructor Sample(int a) call constructor Sample(int a) call copy function call destructor 22 call destructor call destructor */
标签:
原文地址:http://www.cnblogs.com/haocoder/p/4928659.html