C++ 其他数据结构的补充

C++ 其他数据结构

Type aliases (typedef / using)

A type alias is a different name by which a type can be identified. In C++, any valid type can be aliased so that it can be referred to with a different identifier.

alias 别名,化名

使用typedef来定义数据的其他别名,这样做的目的可以让数据更加整齐。

例如,表示学号和成绩都用int类型,这样看起来很繁琐,你可以采用将数据类型改为其他名字的方法,这样就可以达到整齐分类的效果了,数据小了不明显,但大了之后效果就很明显了。

typedef char C;
typedef unsigned int WORD;
typedef char * pChar;
typedef char field [50]; 
C mychar, anotherchar, *ptc1;
WORD myword;
pChar ptc2;
field name; 

Enumerated types with enum class

But, in C++, it is possible to create real enum types that are neither implicitly convertible to int and that neither have enumerator values of type int, but of the enum type itself, thus preserving type safety. They are declared with enum class (or enum struct) instead of just enum:

在C++中,可以来创建真正的枚举类型,它们既不是来隐式转换为int类型,也不是有计数器来计得其类型本身,而是本来就是其枚举类型,这样更安全的保护它的值。

这样来声明有关变量

enum class Colors {black, blue, green, cyan, red, purple, yellow, white};

然后这样使用,记住需要命名空间,举个例子就会很好理解:

#include <iostream>
using namespace std;

enum class Colors{black,blue,green,cyan};

int main()
{
    Colors a;
    a=Colors::black;

    if(a==Colors::black)
        cout << "hello world\n";


    return 0;
}

注意使用C++的拓展可能带来某些未知的警告,这里我们不去管它就好。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值