拷贝构造函数

拷贝构造函数

编译器会默认提供一个浅拷贝的构造函数

一旦手动提供了一个拷贝构造函数,编译器将不再提供默认的拷贝构造函数

1
2
3
4
5
6
7
class 类名
{
类名(const 类名 & another)
{
拷⻉贝构造体
}
}
1
2
3
4
5
6
7
class A
{
A(const A & another)
{

}
}

test.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#pragma once
class test
{
public:
test();
test(int a,int b);
test(int a);
//拷贝构造函数
test(const test & another);
//赋值操作符函数
void operator=(const test & another);


~test();
void print();
private:
int mA;
int mB;
};

test.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include "test.h"
#include<iostream>

using namespace std;
test::test()
{
mA = 0;
mB = 0;
}

test::test(int a, int b)
{
mA = a;
mB = b;
}

test::test(int a)
{
mA = a;
mB = 0;
}

test::test(const test & another)
{
mA = another.mA;
mB = another.mB;
cout << "我是拷贝构造函数" << endl;
}

void test::operator=(const test & another)
{
mA = another.mA;
mB = another.mB;
cout << "我是赋值操作符函数" << endl;
}


test::~test()
{
cout << "~test" << endl;
}

void test::print()
{
cout << mA << endl;
cout << mB << endl;

}

main.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
#include<iostream>
#include"test.h"
using namespace std;

int main(int argc, char* argv[])
{
test t1(100, 200);
test t2(111);
test t3(t2);//调用拷贝构造函数
test t4 = t3;//这里调用的是拷贝构造函数,因为是初始化
t4 = t2; //这里是调用赋值操作符函数,因为不是初始化
return 0;
}