提交 fc29a5c9 编写于 作者: W wsb

增加静态成员的使用示例!

上级 5967fc38
...@@ -3,4 +3,4 @@ project(cpp_10_defineClass) ...@@ -3,4 +3,4 @@ project(cpp_10_defineClass)
set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD 11)
add_executable(cpp_10_defineClass main.cpp Student.cpp Student.h Book.cpp Book.h friendFunc.cpp friendFunc.h ThisDemo.cpp ThisDemo.h) add_executable(cpp_10_defineClass main.cpp Student.cpp Student.h Book.cpp Book.h friendFunc.cpp friendFunc.h ThisDemo.cpp ThisDemo.h staticDemo.cpp staticDemo.h)
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
#include "Book.h" #include "Book.h"
#include "friendFunc.h" #include "friendFunc.h"
#include "ThisDemo.h" #include "ThisDemo.h"
#include "staticDemo.h"
//使用online关键字申明一个内联函数:执行内容简单,使用inline修饰,凡是出现内联函数调用的地方编译器均会赋值副本。整体上是以空间换取时间。 //使用online关键字申明一个内联函数:执行内容简单,使用inline修饰,凡是出现内联函数调用的地方编译器均会赋值副本。整体上是以空间换取时间。
inline int max(int a,int b){ inline int max(int a,int b){
...@@ -60,8 +61,30 @@ int main() { ...@@ -60,8 +61,30 @@ int main() {
ThisDemo thisDemo; ThisDemo thisDemo;
thisDemo.printAge(23); thisDemo.printAge(23);
//类指针的使用示范: 申明一个类指针,把book变量的地址赋予它
Book *bookPointer=&book;
//使用类指针访问类的成员
bookPointer->disValue(book);
//创建多个对象,看看静态成员的内存地址是否会变化
staticDemo demo,demo1,demo2,demo3;
int a=demo.count+1;
int b=demo1.count+2;
int c=demo2.count+3;
int d=demo3.count+4;
cout<<"count的指针地址:"<<&(demo.count)<<","<<&(demo1.count)<<","<<&(demo2.count)<<","<<&(demo3.count)<<endl;
//输出结果为: 0x7ff7e4779090,0x7ff7e4779090,0x7ff7e4779090,0x7ff7e4779090 ,可以发现四个对象的count始终只有一个副本
cout<<"值变化:"<<a<<","<<b<<","<<c<<","<<d<<","<<endl;
demo.printCount();
demo1.printCount();
demo2.printCount();
demo3.printCount();
//也可以直接访问public修饰的静态成员
staticDemo::count=100;
staticDemo::printCount();
return 0; return 0;
} }
//
// Created by 11010 on 2023/4/8.
//
#include "staticDemo.h"
#include <iostream>
using namespace std;
//在外部使用类访问修饰符:: 初始化静态成员变量
int staticDemo::count=0;
void staticDemo::printCount() {
for (int i = 0; i < 100; ++i) {
count++;
}
cout<<"总次数为:"<<count<<endl;
}
//
// Created by 11010 on 2023/4/8.
//
#ifndef CPP_10_DEFINECLASS_STATICDEMO_H
#define CPP_10_DEFINECLASS_STATICDEMO_H
class staticDemo {
public:
//使用static申明成员变量与函数: 静态成员为类所共享,且静态成员会一致存在,无论创建多少个类的对象均只有一个内存副本。
static int count;
static void printCount();
};
#endif //CPP_10_DEFINECLASS_STATICDEMO_H
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册