当前位置:网站首页>static数据成员
static数据成员
2022-08-03 06:22:00 【GarryLau】
1.1 static constexpr成员和static const成员的异同
#include <iostream>
namespace test_static {
class Account {
public:
Account(int peroid = 9):peroid_1_(peroid){
}
static double rate(){
return interest_rate_;
}
static double getPeroid_2_(){
return peroid_2_;
}
private:
static constexpr double interest_rate_ = 0.395; // [RIGHT]静态常量表达式,只能在类内提供初始值
// static const double interest_rate_ = 0.395; // [ERROR]error: 'constexpr' needed for in-class initialization of static data member 'const double test_static::Account::interest_rate_' of non-integral type
static int peroid_;
const int peroid_1_;
static const int peroid_2_ = 0; // [+],static const类型的成员可在类内初始化或类外初始化,如果类内初始化了,类外可不再定义,但一般还是会在类外定义
};
int Account::peroid_ = 30; // [RIGHT]
constexpr double Account::interest_rate_; // 此句可写、可不写,通常应该写;但此时不能再指定初始值了
//const int Account::peroid_2_; // [++],此句可写、可不写,通常应该写,如果类内初始化过了此处不可再赋值,如果类内没初始化此处需要初始化
auto main() -> int {
std::cout << "testing test_static......\n" << std::endl;
Account acc;
std::cout << acc.rate() << std::endl;
std::cout << Account::rate() << std::endl;
std::cout << Account::getPeroid_2_() << std::endl;
std::cout << "------------------------------" << std::endl;
return 0;
}
}
由以上可知,static constexpr成员和static const成员的相同点是,均只能初始化一次。
不同点是,static const可在类内或类外进行初始化,但static constexpr只能类内初始化
1.2 静态成员能用于某些场景,而普通成员不能
#include <iostream>
namespace test_static {
class Bar {
public:
Bar& clear(int i = bg); // 静态成员和普通成员的区别1:静态成员可以作为默认实参
private:
static Bar mem1; /* 静态成员和普通成员的区别2:静态成员独立于任何对象,因此,在某些非静态数据成员可能非法的场合,静态成员却可以正常使用 例如本示例中,静态数据成员可以是不完全类型 */
// Bar mem2; // 错误,数据成员必须是完全类型
static int bg;
};
auto main() -> int {
std::cout << "testing test_static......\n" << std::endl;
std::cout << "------------------------------" << std::endl;
return 0;
}
}
边栏推荐
猜你喜欢

分布式数据库数据一致性的原理、与技术实现方案

深入理解IO流(第一篇)

解决登录vCenter提示“当前网站安全证书不受信任“

el-tabs(标签栏)的入门学习

C语言版本和GCC版本

el-table gets the data attribute of a row in the read data table

关于NOI 2022的报到通知

【着色器实现HandDrawn简笔画抖动效果_Shader效果第十二篇】

QT信号与槽

empty() received an invalid combination of arguments - got (tuple, dtype=NoneType, device=NoneType),
随机推荐
CISP-PTE Zhenti Demonstration
spark中的cache和checkpoint
力扣解法汇总622-设计循环队列
pyspark --- 统计多列的众数并一次返回
CDGA|如何加强数字政府建设?
Embedding two implementations of the torch code
信息学奥赛一本通T1453:移动玩具
伦敦银现货市场如何使用多条均线?
请手撸5种常见限流算法!面试必备
现货黄金分析的主要流派
关于Attention的超详细讲解
El - tree to set focus on selected highlight highlighting, the selected node deepen background and change the font color, etc
【着色器实现Glow可控局部发光效果_Shader效果第十三篇】
被数据分析重塑的5个行业
unity 摄像机旋转拖拽缩放场景
最新版图书馆招聘考试常考试题重点事业单位
信息学奥赛一本通T1448:深搜的剪枝技巧 电路维修
DIFM网络详解及复现
Flink的Exactly-Once、状态机制、watermark机制
信息学奥赛一本通T1447:靶形数独