inline 关键字用于内联函数,在调用时直接插入代码,提高性能;static 关键字用于声明函数或变量在程序中只有一个副本,常用于定义类中静态成员函数和全局变量。
C++ 函数的 inline 和 static 关键字详解
简介
在 C++ 中,inline 和 static 关键字用于修饰函数或变量,以优化代码性能和管理内存。
inline 关键字
inline 关键字指示编译器尝试将函数内联到调用它的代码中。这意味着函数代码的副本将直接插入到调用它的位置,而不是通过函数调用进行跳转。这种技术可以提高性能,因为它减少了函数调用的开销。
语法:
inlinefunction_name(arguments) { // 函数体 }
代码示例:
inline int square(int x) { return x * x; }
在这个例子中,square 函数被声明为 inline。当调用 square 时,它的代码将直接插入到调用它的位置,而不是通过函数调用跳转。
static 关键字
static 关键字用于声明函数或变量在整个程序中只有一个副本。它主要用于以下目的:
语法:
// 静态函数 staticfunction_name(arguments); // 静态变量 static variable_name;
代码示例:
// 静态全局变量 static int global_count = 0; // 静态成员函数 class MyClass { public: static void display_count() { std::cout在这个例子中,
global_count
是一个静态全局变量,它的值在整个程序中都是唯一的。MyClass::display_count
是一个静态成员函数,它可以访问静态变量global_count
。实战案例
使用 inline 加速小型函数:
inline void swap(int& a, int& b) { int temp = a; a = b; b = temp; }使用 static 存储全局数据:
static std::vectordata; void add_to_data(int value) { data.push_back(value); } void get_data() { for (const auto& element : data) { std::cout C++免费学习笔记(深入):立即学习
>在学习笔记中,你将探索 C++ 的入门与实战技巧!
简单总结position定位和元素水平垂直居中
position
position的属性值共有四个常用的:relative、absolute、fixed、static。
首先普及一下文档流的知识:显示元素对象在窗口排列时所占用的位置,自上而下,从左到右。脱离文档流会影响其他元素的位置。
relative:相对定位,不脱离文档流,在文档流原先的位置进行位移。
absolute:绝对定位,脱离文档流,相对于最近的且不为static的父元素进行定位,把父级当成参考物。无父级则相对于body定位。(body和浏览器窗口不是同一个概念,比如body可以设置宽高和边距)
fixed:固定定位,脱离文档流,相对于浏览器窗口定位,不随滚动条滚动而改变位置。
static:默认值,常用到的top、left、bottom、right会失效。
水平垂直居中
常用的四种元素水平垂直居中的方法:
a.父级相对定位,自级绝对定位
div{ position:relative; } p{ position:absolute; width:100px; height:100px; left:50%; top:50%; margin-left:-50px; //这两行代码也可以替换成 margin-top:-50px; //transform:translate(-50%,-50%); }
b.父级display:flex,子级margin:auto
div{ display:flex; } p{ margin:auto; }
c.flex布局
div{ display:flex; justify-content:center; //主轴方向水平居中 align-items:center; //交叉轴垂直居中 }
d.定位+margin:auto法
div{ position:relative; width: 100px; height: 100px; } p{ width: 50px; height: 50px; position:absolute; margin:auto; top:0; left:0; right:0; bottom:0 }