Father.hpp

1 //
2 // Created by Administrator on 2021/7/15.
3 //
4
5 #ifndef C__TEST01_FATHER_HPP
6 #define C__TEST01_FATHER_HPP
7
8
9 class Father {
10 public:
11 Father(){
12 this->age = 100;
13 }
14 ~Father(){}
15 //静态成员函数只能访问静态变量
16 static void getName(){
17 name = "niao";
18 cout<<"name = "<<name<<endl;
19 }
20 void getAge(){
21 cout<<"age = "<<this->age<<endl;
22 }
23 private:
24 static string name;
25 int age;
26 };
27 //很重要,静态成员变量必须在外面初始化
28 string Father::name = "niao";
29 #endif //C__TEST01_FATHER_HPP

Son.hpp

1 //
2 // Created by Administrator on 2021/7/15.
3 //
4
5 #ifndef C__TEST01_SON_HPP
6 #define C__TEST01_SON_HPP
7
8 #include "Father.hpp"
9
10 class Son: public Father{
11 public:
12 Son(){
13 this->age = 50;
14 }
15 ~Son(){}
16 static void getName(){
17 cout<<"name = "<<name<<endl;
18 }
19 void getAge(){
20 cout<<"age = "<<this->age<<endl;
21 }
22 private:
23 static string name;
24 int age;
25 };
26
27 string Son::name = "bie";
28 #endif //C__TEST01_SON_HPP

main.cpp

1 #include <iostream>
2 using namespace std;
3
4 //#include "person.cpp"
5 //类模板里面的成员函数写在cpp只能这么调用
6 #include "Father.hpp"
7 #include "Son.hpp"
8
9 int main() {
10 //通过对象名调用
11 Father *father = new Father();
12 Son son;
13 father->getName();
14 father->getAge();
15 son.getName();
16 son.getAge();
17
18 //通过类名调用
19 //Father::getAge();不是静态的
20 cout<<"通过类名调用"<<endl;
21 Father::getName();
22 Son::getName();
23 Son::Father::getName();
24
25 delete(father);
26 return 0;
27 }

 

主要是给自己看的,所以肯定会出现很多错误哈哈哈哈哈