您的位置:首页 > 编程语言 > C语言/C++

c++学习笔记(二):数据类型

2016-07-21 10:46 561 查看
当使用任何编程语言编程,需要使用不同的变量来存储各种信息。变量是保留在内存位置用来存储值。这意味着,当创建一个变量,需要在内存中保留一些空间。

想要存储像字符的各种数据类型,宽字符,整数,浮点,双浮点,布尔等。基于一个变量的数据类型的信息,在操作系统中分配内存,并决定什么可以被存储在保留的内存。


原始的内置类型:

类型关键字
布尔bool
字符char
整型int
浮点float
双浮点double
无值void
宽字符wchar_t
几种的基本类型可以使用一种这些类型的修饰符或多个被修改:

signed

unsigned

short

long

类型典型位宽典型范围
char1byte-127 to 127 or 0 to 255
unsigned char1byte0 to 255
signed char1byte-127 to 127
int4bytes-2147483648 to 2147483647
unsigned int4bytes0 to 4294967295
signed int4bytes-2147483648 to 2147483647
short int2bytes-32768 to 32767
unsigned short intRange0 to 65,535
signed short intRange-32768 to 32767
long int4bytes-2,147,483,647 to 2,147,483,647
signed long int4bytessame as long int
unsigned long int4bytes0 to 4,294,967,295
float4bytes+/- 3.4e +/- 38 (~7 digits)
double8bytes+/- 1.7e +/- 308 (~15 digits)
long double8bytes+/- 1.7e +/- 308 (~15 digits)
wchar_t2 or 4 bytes1 wide character
变量的大小如上表显示,这取决于编译器和正在使用的计算机而不同。

下面是一个例子,这将产生的各种数据类型的正确大小的计算机上。

#include<iostream>

using namespace std;

int main()
{
cout<<"sizeof(char)="<<sizeof(char)<<endl;
cout<<"sizeof(unsigned char)="<<sizeof(unsigned char)<<endl;
cout<<"sizeof(signed char)="<<sizeof(signed char)<<endl;
cout<<"sizeof(int)="<<sizeof(int)<<endl;
cout<<"sizeof(unsigned int)="<<sizeof(unsigned int)<<endl;
cout<<"sizeof(signed int)="<<sizeof(signed int)<<endl;
cout<<"sizeof(short int)="<<sizeof(short int)<<endl;
cout<<"sizeof(unsigned short int)="<<sizeof(unsigned short int)<<endl;
cout<<"sizeof(signed short int)="<<sizeof(signed short int)<<endl;
cout<<"sizeof(long int)="<<sizeof(long int)<<endl;
cout<<"sizeof(signed long int)="<<sizeof(signed long int)<<endl;
cout<<"sizeof(unsigned long intt)="<<sizeof(unsigned long int)<<endl;
cout<<"sizeof(float)="<<sizeof(float)<<endl;
cout<<"sizeof(double)="<<sizeof(double)<<endl;
cout<<"sizeof(long double)="<<sizeof(long double)<<endl;
cout<<"sizeof(unsigned long int)="<<sizeof(unsigned long int)<<endl;
cout<<"sizeof(wchar_t)="<<sizeof(wchar_t)<<endl;

return 0;
}





typedef声明:

可以创建一个新的名称为现有类型使用typedef。以下是简单的语法使用的typedef来定义新类型:
typedef type newname;


例如,下面告诉编译器,feet是另一个int名字:
typedef int feet;


现在,下面的声明是完全合法的,并创建一个整型变量称为distance:
feet distance;



枚举类型:

枚举类型声明的可选类型名和一组零个或多个标识符可以被用作类型的值。每个枚举是一个常量,其类型是枚举。

要创建一个枚举需要使用关键字enum。枚举类型的一般形式是: 
enum enum-name { list of names } var-list;


在这里,enum-name是枚举的类型名称。名称的列表以逗号分隔。

例如,下面的代码定义的颜色称为colors枚举和c型颜色的变量。最后,c的分配值为“blue”。

enum color { red, green, blue } c;
c = blue;


缺省情况下,第一个名字的值是0,第二个名字的值为1,第三的值为2,依此类推。但是可以通过添加一个初始化给出一个名称的特定值。例如,在下面列举,green的值为5。
enum color { red, green=5, blue };


这里,blue 的值为6,因为每个名字会比它前面的值大1。

#include<iostream>

using namespace std;

typedef int fxl;

enum color{red,green,yellow};

int main()
{
cout<<"sizeof(fxl)="<<sizeof(fxl)<<endl;

color a;
a=red;
cout<<"a="<<a<<endl;

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: