- CPP的类可以有很多种方式进行初始化,大致可以分为一下几种:
- 通过构造函数初始化。
Bozo(const char* name,const char* name); Bozo bozetta = Boze("Bozetta", "Biggens"); Bozo fufu("Fufu", "O'Dweeb"); Bozo *pc = new Bozo("Popo", "Le Peu"); //上面的这种方式创建的类,需要在程序结束的时候delete掉。
- 通过列表初始化。
Bozo bozetta = {"Bozetta", "Biggens"}; Bozo fufu{"Fufu", "O'Dweeb"}; Bozo *pc = new Bozo{"Popo", "Le Peu"};
- 如果构造函数只有一个参数,可以进行下面方式的初始化。
Bozo dribble = Bozo(40); Bozo roon(66); Bozo tubby = 32;
- 通过构造函数初始化。
- 针对于一些类中相关数据需要使用的但是作用域为类的常量可以使用一下两种方式来定义:
- 通过静态常变量定义,(注:只有整形才能在类中被初始化)
class Bakery { private: static const int Months = 12; double costs[Months]; ... }
- 通过枚举类型定义
class Bakery { private: enum { Months = 12; }; double costs[Months]; }
- 通过静态常变量定义,(注:只有整形才能在类中被初始化)
- 为解决相同变量名在不同枚举类型参数错误,CPP11引入新的枚举,但是该枚举类型不能相互隐式为其他类型,只能显示转换,枚举类型的基础类型可以为各种整形和字符串类型,但是不能是其他类型。
#include<iostream> enum egg { kSmall, kMedium, kLarge, kJumbo }; enum class t_shirt { kSmall, kMedium, kLarge, kJumbo }; enum class Box { kSmall, kMedium, kLarge, kJumbo }; enum class VectorRotation : long int { VectorX, VectorY, VectorZ }; enum class Vector : char { VectorX, VectorY, VectorZ }; int main() { t_shirt rolf = t_shirt::kMedium; Box cube = Box::kLarge; egg one = kMedium; int ring = int(rolf); int king = one; if (king < kJumbo) std::cout << "Less" << std::endl; if (ring == int(rolf)) { std::cout << "Yes" << std::endl; } return 0; }
Less Yes
cpp primer plus笔记08-抽象和类
最新推荐文章于 2024-06-12 16:51:14 发布