静态成员函数和静态成员变量,以及继承
发布时间:2023-01-12 15:00:12 361
相关标签: # ios
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 = "<19 }
20 void getAge(){
21 cout<<"age = "<age< 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 = "<18 }
19 void getAge(){
20 cout<<"age = "<age< 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
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<<"通过类名调用"<21 Father::getName();
22 Son::getName();
23 Son::Father::getName();
24
25 delete(father);
26 return 0;
27 }
主要是给自己看的,所以肯定会出现很多错误哈哈哈哈哈
文章来源: https://blog.51cto.com/u_14943525/5435669
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报