[size=xx-large]1.我是新手,我会犯错[/size]
[size=large]运行这个代码,从得到的结果中可以看出,在代码行Child c2 = c;并没有执行赋值符号中的内容,而是执行了拷贝构造函数中的内容。
为什么呢?这是我这个新手容易犯的错误。虽然Child c2 = c;使用了赋值符号,但是此处是对对象c2的定义,也就是说对象c2在没有被构造之前是不能赋值的,因此,编译器在56行代码处会调用拷贝构造函数,而不是我理解的赋值操作。
因此,为了避免这种二义性,对于对象的定义,在c++中最好使用建议的定义方式,如下面的代码[/size]
[size=xx-large]2.继承之间的构造函数如何使用[/size]
运行结果:
[quote]Parent()
Member()
Child()
Parent(const Parent&)
Member(const Member&)
~Child()
~Member()
~Parent()
~Child()
~Member()
~Parent()[/quote]
[size=large]
可以看到,我们注释了类Child的拷贝构造函数,因此,编译器会默认为我们生成一个类Child的拷贝构造函数,这个函数的只能包括:调用父类的拷贝构造函数,然后调用成员变量的拷贝构造函数(如果存在对象成员变量)。那么,如果我们显示的定义Child的拷贝构造函数呢?[/size]
32 class Child {
33 int i;
34 //Member m;
35 public:
36 Child() : i(0) {
37 cout << "Child()" << endl;
38 }
39
40 Child(const Child& c) : Parent(c), i(c.i) {
41 cout << "Child(const Child&)" << endl;
42 }
43
44 Child& operator=(const Child& c) {
45 i = c.i;
46 cout << "Child& operator=(const Child&)" << endl;
47 }
48 ~Child() {
49 cout << "~Child()" << endl;
50 }
51 };
52
53 int main() {
54 Child c;
55
56 Child c2 = c;
57
58 }
[size=large]运行这个代码,从得到的结果中可以看出,在代码行Child c2 = c;并没有执行赋值符号中的内容,而是执行了拷贝构造函数中的内容。
为什么呢?这是我这个新手容易犯的错误。虽然Child c2 = c;使用了赋值符号,但是此处是对对象c2的定义,也就是说对象c2在没有被构造之前是不能赋值的,因此,编译器在56行代码处会调用拷贝构造函数,而不是我理解的赋值操作。
因此,为了避免这种二义性,对于对象的定义,在c++中最好使用建议的定义方式,如下面的代码[/size]
53 int main() {
54 Child c;
55
56 Child c2(c);
57
58 }
[size=xx-large]2.继承之间的构造函数如何使用[/size]
1 #include <iostream>
2 using namespace std;
3
4 class Parent {
5 int i;
6 public:
7 Parent() : i(0) {
8 cout << "Parent()" << endl;
9 }
10 Parent(const Parent& p) : i(p.i) {
11 cout << "Parent(const Parent&)" << endl;
12 }
13 ~Parent() {
14 cout << "~Parent()" << endl;
15 }
16 };
17
18 class Member {
19 int i;
20 public:
21 Member() : i(0) {
22 cout << "Member()" << endl;
23 }
24 Member(const Member& m) : i(m.i) {
25 cout << "Member(const Member&)" << endl;
26 }
27 ~Member() {
28 cout << "~Member()" << endl;
29 }
30 };
31
32 class Child : public Parent {
33 int i;
34 Member m;
35 public:
36 Child() : i(0) {
37 cout << "Child()" << endl;
38 }
39 /*
40 Child(const Child& c) : Parent(c), i(c.i) {
41 cout << "Child(const Child&)" << endl;
42 }
43 */
44 Child& operator=(const Child& c) {
45 i = c.i;
46 cout << "Child& operator=(const Child&)" << endl;
47 }
48 ~Child() {
49 cout << "~Child()" << endl;
50 }
51 };
52
53 int main() {
54 Child c;
55
56 Child c2(c);
57 }
运行结果:
[quote]Parent()
Member()
Child()
Parent(const Parent&)
Member(const Member&)
~Child()
~Member()
~Parent()
~Child()
~Member()
~Parent()[/quote]
[size=large]
可以看到,我们注释了类Child的拷贝构造函数,因此,编译器会默认为我们生成一个类Child的拷贝构造函数,这个函数的只能包括:调用父类的拷贝构造函数,然后调用成员变量的拷贝构造函数(如果存在对象成员变量)。那么,如果我们显示的定义Child的拷贝构造函数呢?[/size]