13.14 使用合成的拷贝控制成员,则直接复制mysn的值,f(a), f(b), f(c)输出相同的结果。
13.15 使用自定义的拷贝构造函数生产新序号,会改变结果。但b=a, c=b,及三次调用f(),都运行了拷贝构造函数,每次都产生新的序号,因此f(a), f(b), f(c)的输出和a, b, c中的mysn值并不相同。
13.16 参数使用const numbered&会改变输出结果,此时b=a, c=b会调用拷贝构造函数,调用f()不会使用拷贝构造函数,而是直接输出参数的mysn值,因此f(a), f(b), f(c)的输出和a, b, c中的mysn值相同。
13.17 第一个测试代码,使用合成的拷贝构造函数:
#include <iostream>
using namespace::std;
class numbered {
public:
numbered() {mysn = num++;} //定义默认构造函数
int mysn = 0;
private:
static int num;
};
int numbered::num = 0;
void f(numbered s)
{
cout << s.mysn << endl;
}
int main()
{
numbered a, b = a, c = b;
f(a);
f(b);
f(c);
return 0;
}
运行输出 0 0 0
第二个代码定义了拷贝构造函数:
#include <iostream>
using namespace::std;
class numbered {
public:
numbered() { mysn = num++; } //定义默认构造函数
numbered(const numbered &r) { mysn = num++; } //拷贝构造函数
int mysn = 0;
private:
static int num;
};
int numbered::num = 0;
void f(numbered s)
{
cout << s.mysn << endl;
}
int main()
{
numbered a, b = a, c = b;
f(a);
f(b);
f(c);
return 0;
}
输出 3 4 5
第三段代码将f()的参数改为引用形式
#include <iostream>
using namespace::std;
class numbered {
public:
numbered() { mysn = num++; } //定义默认构造函数
numbered(const numbered &r) { mysn = num++; } //拷贝构造函数
int mysn = 0;
private:
static int num;
};
int numbered::num = 0;
void f(const numbered &s) //参数为引用
{
cout << s.mysn << endl;
}
int main()
{
numbered a, b = a, c = b;
f(a);
f(b);
f(c);
return 0;
}
输出 0 1 2
1万+




被折叠的 条评论
为什么被折叠?



