当前位置:网站首页>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;
}
}
边栏推荐
- Detailed explanation and reproduction of AlexNet network
- El - tree to set focus on selected highlight highlighting, the selected node deepen background and change the font color, etc
- Charles capture shows
solution - 伦敦银现货市场如何使用多条均线?
- mysql慢查询优化
- 关于利用canvas画带箭头的直线旋转
- 多线程案例
- uniapp 请求接口封装
- Scala 基础 (三):运算符和流程控制
- Flutter | 判断 Text 组件是否显示完
猜你喜欢
随机推荐
pyspark---对suuid区间编码(基于曝光数、点击数)
Chrome插件开发入门
MySQL 数据库基础知识(系统化一篇入门)
第五章:指令集
【playwright】pytest-playwright增加代理服务选项
解决登录vCenter提示“当前网站安全证书不受信任“
连续型特征做embedding代码示例
《多线程案例》阻塞队列、定时器、线程池、饿汉与懒汉模式
MySQL必知必会
MySQL 日期时间类型精确到毫秒
FiBiNet torch reproduction
FiBiNet torch复现
现货黄金分析的主要流派
Flutter | 判断 Text 组件是否显示完
volatile
第六章:存储系统
mysql 时间字段默认设置为当前时间
Scala 高阶(八):集合内容汇总(下篇)
MySQL的DATE_FORMAT()函数将Date转为字符串
Embedding的两种实现方式torch代码








