静态成员函数和静态成员变量,以及继承

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 }
复制代码

 

posted @   蘑菇王国大聪明  阅读(103)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示