当前位置:网站首页>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;
}
}
边栏推荐
猜你喜欢
随机推荐
word之图表目录中点号位置提升3磅
Chrome 配置samesite=none方式
Detailed explanation and reproduction of AlexNet network
nacos-2.0.3启动报错出现no datasource set的坑
多线程案例
重量级大咖来袭:阿里云生命科学与智能计算峰会精彩内容剧透
学会可视化大屏布局技巧,让领导都赞不绝口
El - table column filter functions, control columns show and hide (effect and easy to implement full marks)
线程基础(二)
Nacos单机模式的安装与启动
力扣解法汇总622-设计循环队列
excel高级绘图技巧100讲(二十一)- Excel层叠柱形图
MySQL - 视图操作
Spark 的架构与作业提交流程
华为设备配置BFD与接口联动(触发与BFD联动的接口物理状态变为Down)
ISIJ 2022收官,中国初中生再展风采
七夕和程序员有毛关系?
华为设备BFD配置命令
(十四)51单片机——LCD1602实现滚动效果
IEEE RAL投初稿








