C/C++拷贝构造函数举例
目录
1.拷贝构造函数定义
2.默认拷贝构造函数
3.显式拷贝构造函数
4.参数传递时,调用拷贝构造函数
5.对象作为返回值,调用拷贝构造函数
6.拷贝构造函数,危害(浅拷贝)
7.拷贝构造函数,常用(深拷贝)
8.拷贝构造函数,私有(深拷贝)
正文
1. 拷贝构造函数定义
拷贝构造函数是一种对构造函数的重载。与构造函数有着相同的作用,在创建新对象时,将数值赋值给它们的成员函数。
2.默认拷贝构造函数
若没有将拷贝构造函数显式地定义出来,类具有默认的拷贝构造函数。下记程序里只有带参数arg的构造函数,并未定义拷贝构造函数。
//例1
#include <iostream>
#include <stdio.h>
using namespace std;
class CExample {
private:
int a;
public:
CExample(int arg) {
printf("func: %s\n", __FUNCTION__);
a = arg;
}
void show() {
printf("func:%s, a:%d", __FUNCTION__, a);
}
};
int main()
{
CExample A(100);
CExample B = A; // 或者写为 CExample B(A); 结果一样,都是调用默认拷贝构造函数。
B.show();
return 0;
}
输出:
func: CExample
func:show, a:100
3.显式拷贝构造函数
如果类中显式定义拷贝构造函数,则系统会执行定义的显式构造函数。
//例2
#include <iostream>
#include <stdio.h>
using namespace std;
class CExample {
private:
int a;
public:
CExample(int arg) {
printf("func: %s(int arg)\n", __FUNCTION__);
a = arg;
}
CExample(const CExample &C) {
printf("func: %s(const)\n", __FUNCTION__);
a = C.a;
}
void show() {
printf("func:%s, a:%d", __FUNCTION__, a);
}
};
int main()
{
CExample A(100);
CExample B = A; // 或者写为, CExample B(A);
B.show();
return 0;
}
输出:
func: CExample(int arg)
func: CExample(const)
func:show, a:100
4.参数传递时,调用拷贝构造函数
对象作为函数参数传递给形参时,调用形参的拷贝构造函数。
将对象test作为实参,传递给g_func()函数时,形参CExample C被赋值为test,相当于执行了CExample C=test;
如果类CExample无显式拷贝构造函数,则执行默认构造函数;
下记类CExample有显示拷贝构造函数CExample(const CExample &C){…},执行该函数。
//例3
#include <iostream>
#include <stdio.h>
using namespace std;
class CExample {
private:
int a;
public