函数调用 中 的拷贝构造函数

来源:互联网 发布:分销系统源码 java 编辑:程序博客网 时间:2024/05/24 05:02

 由课后练习13.15引出的问题:

 当函数的形参是类的非引用对象时,实参传入时需要调用拷贝构造函数。

 而当函数的形参是类的引用时,实参传入不需要调用拷贝构造函数。可以理解为,当形参是引用时,直接把实参拿来用,而不用将实参拷贝一份作为形参供函数体使用。

以下用具体函数说明:

该函数要实现 每个类都能独立分配一个id。

(1)类中没有拷贝构造函数时:

#include <iostream>using namespace std;static int index = 0;class numbered{public:numbered() :mysn(++index), data(0){}//numbered(const numbered& ori) :mysn(++index), data(ori.data){ cout << "拷贝构造" << endl; }int mysn;int data;};void f(const numbered s){cout << s.mysn << endl;}int main(){numbered a, b = a, c = b;f(a);f(b);f(c);}

在没有自定义拷贝构造函数时,b = a, c = b,只是简单的a的复制。不能达到静态成员递增的效果。

(2)加入自定义拷贝函数,且函数形参类型为非引用

#include <iostream>using namespace std;static int index = 0;class numbered{public:numbered() :mysn(++index), data(0){}numbered(const numbered& ori) :mysn(++index), data(ori.data){ cout << "拷贝构造" << endl; }int mysn;int data;};void f(const numbered s){cout << s.mysn << endl;}int main(){numbered a, b = a, c = b;f(a);f(b);f(c);}

自定义拷贝函数之后, 

b = a, c = b,调用 两 次拷贝构造函数。

调用f()时,实参拷贝给形参,调用拷贝构造 一 次。

总计三次。

(3)函数形参类型为引用。

#include <iostream>using namespace std;static int index = 0;class numbered{public:numbered() :mysn(++index), data(0){}numbered(const numbered& ori) :mysn(++index), data(ori.data){ cout << "拷贝构造" << endl; }int mysn;int data;};void f(const numbered& s){cout << s.mysn << endl;}int main(){numbered a, b = a, c = b;f(a);f(b);f(c);}

形参类型改为引用后,实参与形参转化的拷贝过程略去。并没有调用拷贝构造函数。







0 0
原创粉丝点击