1 #include <iostream>
2 #include <string>
3
4 using namespace std;
5
6 class Base
7 {
8 public:
9 Base()
10 {
11 name = "base";
12 }
13 Base(string name) :name(name)
14 {
15
16 }
17 virtual void Show()
18 {
19 cout << name << endl;
20 }
21
22 protected:
23 string name;
24 };
25 class Child :public Base
26 {
27 public:
28 Child(int age) : age(age), Base("Child")
29 {
30
31 }
32
33 Child()//默认会调用基类构造函数
34 //Child() :Base() //同上编译器会默认调用基类构造函数
35 //Child() : Base("default") //这样初始化基类,可行
36 {
37 //Base("default"); //此时初始化基类是无效的
38 }
39 void Show() override
40 {
41 cout << name << ":" << age << endl;
42 }
43 private:
44 int age;
45 };
46 int main()
47 {
48 Child tmp(31);
49 tmp.Show();
50
51 //Child tmp2(); //C++不能这样使用 不调⽤任何构造函数创建对象,形式上 其实是声明了⼀个函数⽽已。
52 Child tmp2;
53 tmp2.Show();
54 }