/// MARK: - Aggregate initialization 集合初始化
/// 聚合的定义
/// 1、没有定义 explicit(明确) 构造函数
/// 2、没有使用using声明继承的构造函数
/// 3、没有使用 private 、protected的非静态数据成员
/// 4、没有virtual函数
/// 5 、没有使用 virtual 、 private、 pretected的基类
struct StkInfo{
std::string name;
std::string code;
};
/// 17 可以拥有基类
struct StkDetailInfo : StkInfo {
double price;
double num;
std::string ratio;
double high;
double open;
double low;
double prev_close;
void print_info() const {
std::cout << "StkDetailInfo :" \
<< "\n name : " << name \
<< "\n code : " << code \
<< "\n price : " << price \
<< "\n ratio : " << ratio \
<< "\n high : " << high \
<< "\n open : " << open \
<< "\n low : " << low \
<< "\n prev_close : " << prev_close << std::endl;
}
};
// 从多个基类中派生
template<typename T>
struct StkComplexType : std::string, std::complex<T> {
std::string data;
};
int main(int argc, const char * argv[]) {
//17 结构体初始化
// 使用嵌套{} 初始化
StkDetailInfo detail{{"HKEX", "00388"}, 256.000, 14.800, "-5.51%", 266.000, 265, 250.000, 268.400};
detail.print_info();
// 去掉嵌套初始化的 {}
StkDetailInfo detail1{"HKEX", "00388", 256.000, 14.800, "-5.51%" , 266.000, 265, 250.000, 268.400};
detail1.print_info();
// 初始化为0
StkDetailInfo detail2{};
detail2.print_info();
StkComplexType<float> s { {"HKEX"}, {256.000, 14.800}, "Dec 05 16:08"};
StkComplexType<float> t {"HKEX", {256.000, 14.800}, "Dec 05 16:08"};
// 内部嵌套的初值列表将按照继承时基类声明的顺序传递给基类。
std::cout << s.data << std::endl; // "Dec 05 16:08"
std::cout << static_cast<std::string>(s) << std::endl; // "HKEX"
std::cout << static_cast<std::complex<float>>(s) << std::endl; // {256.000, 14.800}
std::cout << sizeof(decltype(s)) << std::endl;
std::cout << sizeof(float) << std::endl;
// 使用 std::is_aggregate<decltype(s)>::value 判断是否为 aggregate type
std::cout << std::is_aggregate<decltype(s)>::value << std::endl;
return 0;
}
Aggregate initialization 聚合体初始化
最新推荐文章于 2024-08-02 16:46:49 发布