关于C和C++中的基本数据类型int、long、long long、float、double、char、string的大小及表示范围

8 篇文章 0 订阅

一、基本类型的大小及范围的总结(以下所讲都是默认在32位操作系统下):

【单位描述】

   字节:byte

       位:bit

1. 短整型short

    所占内存大小:2byte=16bit;

    所能表示范围:-32768~32767;(即-2^15~2^15-1)

 

2. 整型int

    所占内存大小:4byte=32bit;

    所能表示范围:-2147483648~2147483647;(即-2^31~2^31-1)

    unsigned:  

    所占内存大小:4byte=32bit;

    所能表示范围:0~4294967295;(即0~2^32-1)

 

3. 长整型long

    所占内存大小:4byte=32bit;

    所能表示范围:-2147483648~2147483647;(即-2^31~2^31-1)

    unsigned long:  

    所占内存大小:4byte=32bit;

    所能表示范围:0~4294967295;(即0~2^32-1)

注:上面所说的全部是有符号型的,short,int,long都默认为有符号型,其 中long和int都占4个字节的空间大小,他们有什么区别呢?

       16位操作系统:long:4字节,int:2字节

       32位操作系统:long:4字节,int:4字节

       64位操作系统:long:8字节,int:4字节 

int型在不同位数操作系统中所占用的字节数不同,如果想编写可移植性好的程序,早年流行16位和32位操作系统时最好用long修饰int型,现在流行32位和64位操作系统,用int就挺多了。当然这些都看你怎么去理解它了,毕竟它 们在不同操作系统所占字节数不固定,所以各自都有其适用之处,不可定论其好坏。

下面是对它 们的有科学依据的规定:

C语言规定:无论什么平台都要保证long型占用字节数不小于int型, int型不小于short型。

 

4. 字符型char

    所占内存大小:1byte=8bit;

    所能表示范围:不确定!!!!;

    unsigned char

    所占内存大小:1byte=8bit;

    所能表示范围:0~255;(0~2^8-1)

    singned char:  

    所占内存大小:1byte=8bit;

    所能表示范围:-128~127;(-2^7~2^7-1)

char的默认类型不确定有可能是unsigned,也有可能是signed,主要更具编译器而定,可以自己测试一下编译器的默认char的符号类型。

 

5. 布尔类型bool

    所占内存大小:1byte=8bit;

    所能表示的范围:只能取两个值false或者true;所以最小值就是:0, 最大值:1.

 

6. 单精度float:    

    所占内存大小:4byte=32bit;

    所能表示的范围:(1.17549e-038)~(3.40282e+038);

注意:浮点数在 内存中都是按科学计数法来存储的,浮点数的精度是由尾数的位数决定的,大家记住即可不必深究;

 

7. 双精度double

   所占内存大小:8byte=64bit;

   所能表示的范围:(2.22507e-308)~(1.79769e+308);

注:如何区分和使用这两个浮点类型呢,首先float和double的精度不同, float保留到小数点后面7位,而double保留到小数点后面16位,float能保证6 位有效数字,而double能保证15位有效数字,如果在不追求精度的的情况下当然用 float比较好,节省内存,如果需要很高的精度的情况下,最好还是用 double,平时我们定义浮点型变量一般都用double,毕竟精度高,一般精度 的损失是不能忽略的。

 

8. 字符串string:由于string在c++中属于类类型,不是基本数据类型,类不能计算其在内 存中所占大小,非要用sizeof(string)来算的话,一般算出来的结果是 sizeof(string)=4byte,如果string字符串内容很多,很明显就不是其 真实大小,string类里面有计算其字节大小的函数如:size(),length()。

 

  • 48
    点赞
  • 82
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
用变量a给出下面的定义 a) 一个整型数(An integer) b) 一个指向整型数的指针(A pointer to an integer) c) 一个指向指针的的指针,它指向的指针是指向一个整型数(A pointer to a pointer to an integer) d) 一个有10个整型数的数组(An array of 10 integers) e) 一个有10个指针的数组,该指针是指向一个整型数的(An array of 10 pointers to integers) f) 一个指向有10个整型数数组的指针(A pointer to an array of 10 integers) g) 一个指向函数的指针,该函数有一个整型参数并返回一个整型数(A pointer to a function that takes an integer as an argument and returns an integer) h) 一个有10个指针的数组,该指针指向一个函数,该函数有一个整型参数并返回一个整型数( An array of ten pointers to functions that take an integer argument and return an integer ) 答案是: a) int a; // An integer b) int *a; // A pointer to an integer c) int **a; // A pointer to a pointer to an integer d) int a[10]; // An array of 10 integers e) int *a[10]; // An array of 10 pointers to integers f) int (*a)[10]; // A pointer to an array of 10 integers g) int (*a)(int); // A pointer to a function a that takes an integer argument and returns an integer h) int (*a[10])(int); // An array of 10 pointers to functions that take an integer argument and return an integer 13.下面的数据声明都代表什么? (1)float (**def)[10]; def是一个二级指针,它指向的是一个一维数组的指针,数组的元素都是float. (2)double*(*gh)[10]; gh是一个指针,它指向一个一维数组,数组元素都是double*. (3)double(*f[10])(); f是一个数组,f有10个元素,元素都是函数的指针,指向的函数类型是没有参数且返回double的函数. (4)int *((*b)[10]); 就跟int *(*b)[10]是一样的,b是一维数组的指针. (5)Long (*fun)(int); 函数指针. (6)int (*(*F)(int,int))(int); F是一个函数指针,指向的函数的类型是有两个int参数并且返回一个函数指针的函数,返回的函数指针指向有一个int参数且返回int的函数.  所有的ASCII码都可以用“\”加数字(一般是8进制数字)来表示。而C定义了一些字母前加"\"来表示常见的那些不能显示的ASCII字符,如\0,\t,\n等,就称为转义字符,因为后面的字符,都不是它本来的ASCII字符意思了。   转义字符 意义 ASCII码值(十进制)   \a 响铃(BEL) 007   \b 退格(BS) 008   \f 换页(FF) 012   \n 换行(LF) 010   \r 回车(CR) 013   \t 水平制表(HT) 009   \v 垂直制表(VT) 011   \\ 反斜杠 092   \? 问号字符 063   \' 单引号字符 039   \" 双引号字符 034   \0 空字符(NULL) 000   \ddd 任意字符 三八进制   \xhh 任意字符 二十六进制   字符型常量   字符型常量所表示的值是字符型变量所能包含的值。我们可以用ASCII表达式来表示一个字符型常量,或者用单引号内加反斜杠表示转义字符。   'A', '\x2f', '\013';   其:\x表示后面的字符是十六进制数,\0表示后面的字符是八进制数。   注意:在Turbo C 2.0,字符型常量表示数的范围是-128到127,除非你把它声明为unsigned,这样就是0到255。   上面我们见到的\x,\n,\a等等都是叫转义字符,它告诉编译器需要用特殊的方式进行处理。下面给出所有的转义字符和所对应的意义:   转义字符 描述   \' 单引号   \ 双引号   \\ 反斜杠   \0 空字符   \ccc (最多三)八进制数   \a 声音符   \b 退格符   \f 换页符   \n 换行符   \r 回车符   \t 水平制表符   \v 垂直制表符   \xhh(最多两)十六进制符 下面的代码输出是什么,为什么? 1、sizeof()和strlen()的使用? 答: 1.从功能定义上,strlen函数,用来求字符串的长度,sizeof函数是用来求指定变量或变量类型等所占用内存的 大小; 2.sizeof是运算符,而strlen是C库函数strlen只能用char*做参数,且以'\0'结尾的; 对于静态数组处理: char str[20]="0123456789"; strlen(str)=10; //表示数组字符串的长度 sizeof(str)=20; //表示数组变量分配的长度 对于指针处理: char *str="0123456789"; strlen(str)=10; //表示字符串的长度 sizeof(str)=4; //表示指针变量的所占内存大小 sizeof(*str)=1; //表示'0'这个字符变量的所占内存大小 2、 struct 和 class的区别? 答: (1)类的成员默认是private的,当是可以声明为public,private 和protected,结构定义的成员默认的都是public. (2)结构不允许定义成员函数,当是类可以定义成员函数. (3)结构不可以存在继承关系,当是类可以存在继承关系. 3、 strcpy(), strcat(), strcmp,strlen(), strchr(), memcpy(), memcmp(), memset()的编写? 4、 内存的分配方式的分配方式有几种? 答: (1)从静态存储区域分配。内存在程序编译的时候就已经分配好,这块内存在程序的整个运行期间都存在。例如全局变量。 (2)在栈上创建。在执行函数时,函数内局部变量的存储单元都可以在栈上创建,函数执行结束时这些存储单元自动被释放。栈内存分配运算内置于处理器的指令集,效率很高,但是分配的内存容量有限。 (3)从堆上分配,亦称动态内存分配。程序在运行的时候用malloc或new申请任意多少的内存,程序员自己负责在何时用free或delete释放内存。动态内存的生存期由我们决定,使用非常灵活,但问题也最多。 5,、解释堆和栈的区别? 答: (1)栈区(stack):由编译器自动分配释放 ,存放函数的参数值,局部变量的值等。其操作方式类似于数据结构的栈。 (2)堆区(heap):一般由程序员分配释放, 若程序员不释放,程序结束时可能由OS回收 。注意它与数据结构的堆是两回事,分配方式倒是类似于链表.(主要有:malloc/free,new/delete) 6,、枚举的用法,以及它与宏的区别? 答: 枚举(enum)作用:定义一组常量,而且这些常量组成了一个集合。当我们将emun参数传递给函数时,如果传递了一个不属于这个集合的参数,编译器报错。 区别: 枚举是类型,而宏没有类型。 枚举将检查其语法,而宏是简单的文本替换。 7、 const的用法,以及声明const变量与宏的区别? 答: const的用法有四种: a): const对象和const类型的对象; b): const指针 和 指向const的指针 及两者结合; c): const 参数修饰 和 参数返回类型的const修饰; d): const类成员 和 const 成员函数; 区别: const常量有数据类型, 而宏常量没有数据类型。编译器可以对前者进行类型安全检查,而对后者只能进行字符 替换,没有类型 安全检查。而且字符替换可能会带来料想不到的边界效应。有些集成化工具可以对const常量进行调试, 但不能对宏量进行调试。 8、函数assert的用法? 答:断言assert是仅在debug版本起作用的宏,用于检查“不应该“发生的情况。程序员可以把assert看成一个在任何系统状态下都可以安全使用的无害测试手段。 9、用预处理指令#define 声明一个常数,用以表明1年有多少秒(忽略闰年问题)? 答: #define SECONDS_PER_YEAR (60 * 60 * 24 * 365)UL 10、 写一个"标准"宏MIN,这个宏输入两个参数并返回较小的一个? 答: #define MIN(A,B) ((A) <= (B) ? (A) : (B)) 11、嵌入式系统经常要用到无限循环,你怎么样用C编写死循环呢? 答: 这个问题用几个解决方案。我首选的方案是: while(1) { } 一些程序员更喜欢如下方案: for(;;) { } 13、关于内存对齐的问题以及sizof()的输出? 答: 编译器自动对齐的原因:为了提高程序的性能,数据结构(尤其是栈)应该尽可能地在自然边界上对齐。原因在于,为了访问未对齐的内存,处理器需要作两次内存访问;然而,对齐的内存访问仅需要一次访问。 14、 static有什么用途?(请至少说明两种) 答: (1)在函数体,一个被声明为静态的变量在这一函数被调用过程维持其值不变。 (2) 在模块内(但在函数体外),一个被声明为静态的变量可以被模块内所用函数访问,但不能被模块外其它函数访问。它是一个本地的全局变量。 (3) 在模块内,一个被声明为静态的函数只可被这一模块内的其它函数调用。那就是,这个函数被限制在声明它的模块的本地范围内使用。 15、引用与指针有什么区别? 答: (1) 引用必须被初始化,指针不必。 (2) 引用初始化以后不能被改变,指针可以改变所指的对象。 (3) 不存在指向空值的引用,但是存在指向空值的指针。 16、什么是平衡二叉树? 答: 左右子树都是平衡二叉树 且左右子树的深度差值的绝对值不大于1。 17、堆栈溢出一般是由什么原因导致的? 答: 没有回收垃圾资源。 18、什么是预编译?何时需要预编译? 答: (1)总是使用不经常改动的大型代码体。 (2)程序由多个模块组成,所有模块都使用一组标准的包含文件和相同的编译选项。在这种情况下,可以将所有包含文件预编译为一个预编译头。 19、队列和栈有什么区别? 答: 队列先进先出;栈后进先出。 20、数组和链表的区别? 答: 数组:数据顺序存储,固定大小; 链表:数据可以随机存储,大小可动态改变; 21、为什么数组名作为参数,会改变数组的内容,而其它类型如int却不会改变变量的值? 答: 当数组名作为参数时,传递的实际上是地址。而其他类型如int作为参数时,由于函数参数值实质上是实参的一份拷贝,被调函数内部对形参的改变并不影响实参的值。 22、数据结构和算法: A:查找: (1)二分法查找; B:写出下列算法的时间复杂度和实现排序: (1)冒泡排序; (2)选择排序; (3)插入排序; (4)快速排序; (5)堆排序; (6)归并排序; 23、编写gbk_strlen函数,计算含有汉字的字符串的长度,汉字作为一个字符处理;已知:汉字编码为双字节,其 参数里涉及指针,就要考虑该指针是不是一个需要修改的量,如果是,则参数应采用指向指针的指针。 (C语言里参数传递都是传值,是一个拷贝,修改指针,只是改变了拷贝的指向,原指针指向并没有改变,而修改指针的内容则是可以的。)如果函数的参数是一个指针,不要指望用该指针去申请动态内存。(即上面所说的修改该指针) 编译器总是要为函数的每个参数制作临时副本,指针参数p的副本是 _p,指针参数也不例外。 如果非得要用指针参数去申请内存,那么应该改用“指向指针的指针”,由于“指向指针的指针”这个概念不容易理解,我们也可以用函数返回值来传递动态内存。 常常有人把return语句用错了。这里强调不要用return语句返回指向“栈内存”的指针,因为该内存在函数结束时自动消亡。 c语言里,利用函数的返回值来表明它是否执行成功的做法最常见。 2.如果要在单链表删除或插入一个元素,就必须知道指向删除点或插入点前面那个元素的指针才行。 数组具有随机存取性(可以立即存取任一元素) char *str = "the word" 常量字符串,静态存储区,具有程序生命期。 char *str = (char *)malloc(....); 堆上分配,手动释放,否则内存泄漏。 char str[] = "the word" 栈上分配,函数生命期。 4. '\0'不是指ASCII码值,它是字符,它的ASCII码值是0,也就是ASCII码表的第一个字符。'\0'并非是空格,空格的ASCII码值是32,只不过是输出类似于空格而已。 5. 在32程序里,所有类型的指针的值都是一个32整数,因为32程序里内存地址全都是32长,指针本身占据了4个字节的长度,即用一个字的空间保存一个地址。地址是按字节表示的,一个字节一个地址。地址+1,移动一个字节。 6.从语法上看,你只须把指针声明语句的指针名字和名字左边的指针声明符*去掉,剩下的就是指针所指向的类型。 *p的结果是p所指向的东西 &a的运算结果是一个指针,指针所指向的类型是a的类型,指针所指向的地址嘛,那就是a的地址。 7. 声明了一个数组TYPE array[n],则数组名称array就有了两重含义:第一,它代表整个数组,它的类型是TYPE[n];第二 ,它是一个指针,该指针的类型是TYPE*,该指针指向的内存区就是数组第0号单元,该指针自己占有单独的内存区. 在表达式sizeof(array),数组名array代表数组本身,故这时sizeof函数测出的是整个数组的大小。 sizeof(array+n)测出的是指针类型的大小char类型的长度是一个字节,int类型的长度是4个字节,即一个字。 sizeof()得到的值是以字节为单,所以sizeof(int) = 4 8. char* 相当于stringchar* arr[10]即字符串数组
GreenCppC 2008-8-24 ========================================= // I 类,对象,函数重载 //-------- From C to C++ ------------ // A simple C Program! // convert a string to uppercase! #include <stdio.h> #define N 200 int main(){ char ms[N]; int i; printf("Input ms: "); gets(ms); for(i=0;ms[i];i++) if(ms[i]>='a'&&ms[i]<='z') ms[i]-='\x20'; puts(ms); return 0; } /* path d:\wingw\bin gcc abc.c -o abc.exe */ //------------------------------ // A better C Program! #include <stdio.h> #define N 200 void strUpper(char *s); void strLower(char *s); int main(){ char ms[N]; printf("Input ms: "); gets(ms); strUpper(ms); puts(ms); strLower(ms); puts(ms); return 0; } void strUpper(char *s) { for(;*s;s++) if(*s>='a'&&*s<='z')*s-='\x20'; } void strLower(char *s) { for(;*s;s++) if(*s>='A'&&*s<='Z')*s+='\x20'; } //------------------------------ // A C++ Program without class and object! #include <iostream> using namespace std; const int N=200; void strUpper(char *s); void strLower(char *s); int main(){ char ms[N]; cout<<"Input ms: "; cin.getline(ms,N); strUpper(ms); cout<<ms<<"\n"; strLower(ms); cout<<ms<<endl; return 0; } void strUpper(char *s) { for(;*s;s++) if(*s>='a'&&*s<='z')*s-='\x20'; } void strLower(char *s) { for(;*s;s++) if(*s>='A'&&*s<='Z')*s+='\x20'; } //------------------------------ // A C++ Program with class and object! #include <iostream> using namespace std; const int N=200; class Str{ char s[N]; public: void out(){cout<<s<<"\n";} void in(){cout<<"s: "; cin.getline(s,N);} void upper(); void lower(); }; void Str::upper() {char *p; for(p=s;*p;p++) if(*p>='a'&&*p<='z')*p-='\x20'; } void Str::lower() { for(char *p=s;*p;p++) if(*p>='A'&&*p<='Z')*p+='\x20'; } // - - - int main(){ Str a; cin>>a.s; //error! a.in(); a.upper(); a.out(); a.lower(); a.out(); return 0; } ========================================= // II. 构造与析构函数 #include <iostream> #include <cstring> using namespace std; class child { char name[20]; int age; public: child(); child(char *n,int a); void ask(char *n); void ask(int a); ~child(); }; // --- child::child(){ strcpy(name,"Tomme"); age=3; } // --- child::child(char *name,int age){ strcpy(this->name,name); this->age=age; // this -- address of self object } // --- void child::ask(char *n){ if(!strcmp(name,n)) cout<<"Yes, i am "<<n<<".\n"; else cout<<"No, i am not "<<n<<".\n"; } // --- void child::ask(int age){ if(this->age==age) cout<<"Yes, i am "<<age<<" years old.\n"; else cout<<"No, i am not "<<age<<" years old.\n"; } // --- child::~child(){ cout<<name<<": Bye!\n"; } //---------- int main(){ child tom,rose("Rosie",4); tom.age=4; // error! tom.ask("tom"); rose.ask("Alice"); tom.ask(2); return 0; } ========================================= // III. 继承 #include <iostream> #include <cstring> using namespace std; class child { protected: //note this change! char name[20]; int age; public: child(); child(char *n,int a); void ask(char *n); void ask(int a); }; // --- child::child(){ strcpy(name,"Tomme"); age=3; } // --- child::child(char *n,int a){ strcpy(name,n); age=a; } // --- void child::ask(char *n){ if(!strcmp(name,n)) cout<<"Yes, i am "<<n<<".\n"; else cout<<"No, i am not "<<n<<".\n"; } // --- void child::ask(int a){ if(a==age) cout<<"Yes, i am "<<a<<" years old.\n"; else cout<<"No, i am not "<<a<<" years old.\n"; } // ----------- class pupil: public child{ char book[20]; public: pupil(char *n,int a,char *b); void list(); }; // --- pupil::pupil(char *n,int a,char *b): child(n,a) { strcpy(book,b); } // --- void pupil::list() { cout<<name<<" "<<age<<" "<<book<<"\n"; } //---------- int main(){ child tom,rose("Rosie",4); tom.ask("tom"); rose.ask("Alice"); tom.ask(2); pupil green("Green",9,"Nature"); green.ask("Jack"); green.ask(10); green.list(); return 0; } ========================================= // IV. 增加与基类成员函数同名的函数; // 调用基类成员函数;内联函数(in-line) #include <iostream> #include <cstring> using namespace std; class child { protected: char name[20]; int age; public: child(); child(char *n,int a); void ask(char *n); void ask(int a); }; // --- child::child(){ strcpy(name,"Tomme"); age=3; } // --- child::child(char *n,int a){ strcpy(name,n); age=a; } // --- void child::ask(char *n){ if(!strcmp(name,n)) cout<<"Yes, i am "<<n<<".\n"; else cout<<"No, i am not "<<n<<".\n"; } // --- void child::ask(int a){ if(a==age) cout<<"Yes, i am "<<a<<" years old.\n"; else cout<<"No, i am not "<<a<<" years old.\n"; } // ----------- class pupil: public child{ char book[20]; public: pupil(char *n,int a,char *b); void ask(char *n){child::ask(n);} // in-line! void ask(int a){child::ask(a);} void ask(); }; // --- pupil::pupil(char *n,int a,char *b): child(n,a) { strcpy(book,b); } // --- void pupil::ask() { cout<<name<<" "<<age<<" "<<book<<"\n"; } //---------- int main(){ child tom,rose("Rosie",4); tom.ask("tom"); rose.ask("Alice"); tom.ask(2); pupil green("Green",9,"Nature"); green.ask("Jack"); green.ask(10); green.ask(); return 0; } ===================================== // V. 对象数组 #include <iostream> using namespace std; class C1{ int a,b; public: C1(int m,int n){a=m;b=n;} int getAdd(){return a+b;} }; int main() {C1 ob[3]={C1(1,2),C1(3,4),C1(5,6)}; int i; for(i=0;i<3;i++) cout << ob[i].getAdd() << " "; // C1 oe[2]; -- Error! means constructor is C1() // -- need reload C1::C1(){ ... } // -- eg, C1::C1(){a=b=0;} return 0; } ========================================= // VI. 指向对象的指针 C1 obA(2,3), *p; p=&obA; cout << p->getAdd(); //------------- C1 ob[3]={C1(1,2),C1(3,4),C1(5,6)}, *q; q=ob; for(int i=0;i<3;i++) {cout << q->getAdd() << " "; q++; } //------------- class C2{ public: int a; C2(int k){a=k*k;} }; // . . . C2 obB(9); int *p; p=&obB.a; // Note! a is public, p to member cout << *p; // 指向派生类的指针 class Base{ public: int a,b; Base(int m,int n){a=m;b=n;} int getAdd(){return a+b;} }; class Derived: public Base{ int c; public: Derived(int x,int y,int z): Base(x,y) {c=z;} float getAve(){return (a+b+c)/3.0F;} }; // ... Base *bp; Derived d(6,7,9); bp=&d; cout << bp->getAdd(); cout << bp->getAve(); // Error! cout << ((Derived *) bp) ->getAve(); ========================================= // VII. 动态分配:new, delete #include <iostream> #include <new> using namespace std; int main() {int *p; try{ p=new int; } catch(bad_alloc ex){ cout << "New failed!\n"; return -1; } *p=20; cout << "At "<<p<<" is "<< *p <<"\n"; delete p; return 0; } //------------- #include <iostream> #include <new> using namespace std; int main() {int *p; try{ p=new int[6]; } catch(bad_alloc ex){ cout << "New failed!\n"; return -1; } float ave=0.0F; int i; cout<<"Enter numbers: "; for(i=0;i<6;i++) {cin>>p[i]; ave+= *(p+i); cout<< *(p+i); } ave/=6.0F; cout << "Ave = "<< ave <<"\n"; delete [] p; return 0; } //------------- #include <iostream> #include <cstring> #include <new> using namespace std; class Balance{ char name[40]; double curValue; public: Balance(char *n,double v){ strcpy(name,n); curValue=v; } void getValue(char *n,double &v){ strcpy(n,name); v=curValue; } }; int main() { Balance *p; char s[40]; double bal; try{ p=new Balance("Robin Hood",3536.45); } catch(bad_alloc ex){ cout << "New failed!\n"; return -1; } p->getValue(s,bal); cout<<s<<"\'s balance is "<<bal<<"\n"; delete p; return 0; } ========================================= // VIII. 传递引用 #include <iostream> using namespace std; void neg1(int k); void neg2(int *p); void neg3(int &k); int main() { int x=20; neg1(x); neg2(&x); cout << x<< "\n"; neg3(x); cout << x<< "\n"; } // - - - void neg1(int k) { k=-k;} void neg2(int *p) { *p=-*p;} void neg3(int &k) { k=-k; } //------------- #include <iostream> using namespace std; class C1{ public: int k; void neg(C1 &o){o.k=-o.k;} // -- no temp object created }; int main() { C1 ob; ob.k=20; ob.neg(ob); cout << ob.k <<"\n"; return 0; } //----------------------------------- /* Input a sentence,reverse all the words except other chars, eg: etihw, dna kcalb! => white, and black! NOT: !black and ,white */ #include <iostream> #include <new> #include <cstdlib> #include <cctype> using namespace std; const int N=200; /* - - - - - - */ class CharStack{ const int StkLen; char *data; int top; public: CharStack(); ~CharStack(){delete []data;} int push(char x) {if(top>=StkLen-1)return -1; // it's full top++; data[top]=x; return 0; } int pop(char &x) {if(top<=-1)return -1; // empty! x= *(data+top); top--; return 0; } }; CharStack::CharStack():StkLen(40) {try{ data=new char[StkLen]; }catch(bad_alloc){cout<<"New failed!"; exit(-1);} top=-1; } // --------- class WordRev{ char ms[N]; public: void reads() { cout<<"Input str:\n"; cin.getline(ms,N); } void prints() { cout<<ms<<"\n"; } void wRev(); }; void WordRev::wRev() {CharStack stk; int i=0,wStart,wEnd; while(ms[i]) {if(!isalpha(ms[i]))i++; else {wStart=i; while(isalpha(ms[i]))stk.push(ms[i++]); wEnd=i; i=wStart; while(!stk.pop(ms[i]))i++; i=wEnd; } } } // --------- int main() { WordRev sr; sr.reads(); sr.wRev(); sr.prints(); return 0; } ========================================= // IX 函数形参使用默认值 #include <iostream> #include <cstring> using namespace std; // ----------- class pupil{ public: char name[20]; int age; char book[20]; pupil(char *n,int a,char *b); void list(); }; // --- pupil::pupil(char *n,int a,char *b){ strcpy(name,n); age=a; strcpy(book,b); } // --- void pupil::list() { cout<<name<<" "<<age<<" "<<book<<"\n"; } //---------- void nextYear(pupil &c,char *book="Math"); //---------- int main(){ pupil green("Green",9,"Chinese"); green.list(); nextYear(green); green.list(); nextYear(green,"Nature"); green.list(); return 0; } //---------- void nextYear(pupil &c,char *book="Math") { // ="Math" Should be omitted, for previous prototype c.age++; strcpy(c.book,book); return; } /* D:\green>g++ pupil.cpp -o pupil.exe pupil.cpp: In function `void nextYear(pupil&, char*)': pupil.cpp:41: error: default argument given for parameter 2 of `void nextYear(pupil&, char*)' pupil.cpp:25: error: after previous specification in `void nextYear(pupil&, char*)' */ ========================================= // X. 虚函数 virtual #include <iostream> using namespace std; class base{ public: virtual void vf(){cout<<"base's vf.\n";} }; class derived1:public base{ public: virtual void vf(){cout<<"derived1's vf.\n";} }; class derived2:public base{ public: virtual void vf(){cout<<"derived2's vf.\n";} }; void f(base &r){r.vf();} int main() {base b, *p; derived1 d1; derived2 d2; b.vf(); d1.vf(); d2.vf(); p=&b; p->vf(); p=&d1; p->vf(); // derived1's vf. p=&d2; p->vf(); // derived2's vf. f(b); f(d1); // derived1's vf. f(d2); // derived2's vf. return 0; } ========================================= // XI. 对象赋值问题 #include <iostream> #include <cstdlib> #include <new> using namespace std; class Myclass{ int *p; public: Myclass(int i); void show(){cout<< *p<<"\n";} ~Myclass(){delete p;} }; Myclass::Myclass(int i){ try{ p=new int; } catch(bad_alloc e) {cout<< "New failed!\n"; exit(-1); } *p=i; } int main() {Myclass a(20); Myclass b=a; //copy by bits b.show(); return 0; // 错误!对象 p 所指向的内存空间将被释放 2 次! } ========================================= // XII. 拷贝构造函数 ---- 解决对象参数传递的副作用问题 #include <iostream> #include <new> using namespace std; class array{ public: int *p; int size; array( ){p=NULL;size=0; }; array(int sz); array(const array &a); ~array(){if(!p){delete [ ]p; size=0;}} void input(); }; array::array(int sz){ size=sz; try{ p=new int[size]; }catch (bad_alloc xa){ cout <<"Alloc failed!"; exit(EXIT_FAILURE); } } array::array(const array &a){ try{ p=new int[a.size]; }catch (bad_alloc xa){ cout <<"Alloc failed!"; exit(EXIT_FAILURE); } size=a.size; for(int i=0;i<size;i++)p[i]=a.p[i]; } void array::input(){ cout<<"Input "<<size<<" integers: "; for(int i=0;i<size;i++)cin>>p[i]; } void inc(array a){ int i; for(i=0;i<a.size;i++) if(a.p[i]==59)a.p[i]++; cout<<"Result is: " ; for(i=0;i<a.size;i++)cout<<a.p[i]<<' '; cout<<"\n"; } int main(){ array a(4),c; a.input(); array b(a); // 调用拷贝构造函数 inc(b); //调用拷贝构造函数(隐式) for(int i=0;i<b.size;i++)cout<<b.p[i]<<' '; return 0; } ========================================= // XIII. 运算符重载 #include <iostream> using namespace std; class loc{ int longitude,latitude; public: loc(){} //needed to construct temp objects loc(int lg,int lt){longitude=lg; latitude=lt;} void show(){cout<<longitude<<" "<<latitude<<"\n";} loc operator+(loc op2); loc operator++(); loc operator=(loc op2); loc operator+=(loc op2); }; loc loc::operator+(loc op2) {loc temp; temp.longitude=op2.longitude+longitude; temp.latitude=op2.latitude+latitude; return temp; } loc loc::operator++() //前缀形式 prefix {longitude++; latitude++; return *this; } loc loc::operator=(loc op2) { longitude=op2.longitude; latitude=op2.latitude; return *this; //为连续赋值 } loc loc::operator+=(loc op2) { longigude=op2.longitude+longitude; latitude=op2.latitude+latitude; return *this; //为连续赋值 } // operator=和operator++等都改变了对象的值 int main() {loc ob1(10,20),ob2(5,30),ob3; ob3=ob1+ob2; ++ob3; ob3.show(); ob1+=ob2; ob1=ob1+ob2; // ob1.+(ob2) like (ob1+ob2).show(); ++ob1; ob1=ob2=ob3; ... ... } ========================================= // XIV. 异常的抛出,捕获与处理 #include <iostream> using namespace std; int main() {cout <<"Start\n"; try { cout << "Inside try block\n"; throw 100; cout << "This will not execute"; } catch (int i) { cout << "Caught an exception, value is: "; cout << i <<"\n"; } cout << "End\n"; return 0; } // -------------------- #include <iostream> using namespace std; void xtest(int test) { cout << "Inside xtest!\n"; if(test) throw test; } int main() {cout <<"Start\n"; try { cout << "Inside try block\n"; xtest(0); xtest(1); xtest(2); } catch (int i) { cout << "Caught an exception, value is: "; cout << i <<"\n"; } cout << "End\n"; return 0; } // 捕获异常类 #include <iostream> #include <cstring> using namespace std; class MyException{ public: char how[80]; int what; MyException(){*how=0; what=0;} MyException(char *s, int n) {strcpy(how,s); what=n; } }; int main() {int i; try { cout <<"Enter a positive number: "; cin >> i; if(i<0) throw MyException("Not Positive",i); } catch (MyException e) { cout << e.how<<": "; cout << e.what <<"\n"; } return 0; } // 捕获派生异常类 #include <iostream> using namespace std; class B { }; class D: public B { }; int main() {D derived; try { throw derived; } catch (D d) { cout << "Caught a derived class, not the base! \n"; } catch (B b) { cout << "Caught the base class! \n"; } return 0; } // 异常的限制及捕获所有异常 #include <iostream> using namespace std; void xtest(int test) throw (int,char,double,char *) { try { if(test==0) throw test; if(test==1) throw 'a'; if(test==2) throw 12.34; if(test==3) throw "A string."; } catch (int i) { cout << "Caught an integer!"; } catch (...) { cout << "Caught Another!"; } } int main() {cout <<"Start\n"; xtest(0); xtest(1); xtest(2); xtest(3); cout << "End\n"; return 0; } // 异常的再次抛出 #include <iostream> using namespace std; void xhandler() { try { throw "Hello!"; } catch (const char *) { cout << "Caught a string inside!\n"; throw; //rethrow char * out of function } } int main() {cout <<"Start\n"; try { xhandler(); } catch (const char *) { cout << "Caught a string outside!\n"; } cout << "End\n"; return 0; } // 一个简单的程序 #include <iostream> using namespace std; int main() {int a,b; cout <<"Enter a b: "; cin >> a >> b; try { if(!b) throw b; cout << "Result: "<< a/b << endl; } catch (int i) { cout << "Can't divide by zero!\n"; } return 0; } ========================================= XV. 模板 //模板之通用函数 #include <iostream> using namespace std; template <class X> void superSwap(X &a, X &b) { X t; t=a; a=b; b=t; }; int main() { int m=10, n=20; double x=10.1, y=20.2; char a='A', b='\x42'; superSwap(m,n); superSwap(x,y); superSwap(a,b); cout<<"m="<<m<<", n="<<n<<'\n'; cout<<"x="<<x<<", y="<<y<<'\n'; cout<<"a="<<a<<", b="<<b<<'\n'; return 0; } ---------------------------------- #include <iostream> using namespace std; template <class type1,class type2> void myfunc(type1 x, type2 y) { cout<<x<<' '<<y<<'\n'; } int main() { myfunc("C++ is great!", 100); // char* , int myfunc(1234.56, 20L); // double , long int return 0; } // 模板之通用类 #include <iostream> using namespace std; const int Size=20; template <class DataType> class SuperStack{ DataType data[Size]; int top; public: SuperStack(){top= -1;} int push(DataType x); int pop(DataType &x); }; template <class DataType> int SuperStack<DataType>::push(DataType x) { if(top>=Size-1) return -1; // stack is full data[++top]=x; return 0; } template <class DataType> int SuperStack<DataType>::pop(DataType &x) { if(top<0) return -1; // stack is empty x=data[top--]; return 0; } int main() { SuperStack<char> chStack; SuperStack<double> dbStack; char s[Size]="ABC"; double a[Size]={20.1, 21.2, 22.3}; int i; for(i=0;i<3;i++) { chStack.push(s[i]); dbStack.push(a[i]); } for(i=0;i<3;i++) { chStack.pop(s[i]); dbStack.pop(a[i]); } cout << s << '\n'; for(i=0;i<3;i++) cout << a[i]<<' '; cout<<'\n'; return 0; } ========================================= XVI. 名字空间 #include <iostream> using namespace std; namespace GreenNamespace{ char Say[80]="TRUTH, Must thou Know!"; bool isUpperLetter(char ch) { if(ch>='A' &&ch<='Z')return true; return false; } class X{ public: int year; X(int y){year=y;} }; // note this semi-colon! } using namespace GreenNamespace; int main() {cout << Say <<'\n'; char *p=Say; int count=0; for(;*p;p++) if(isUpperLetter(*p))count++; cout << "count = " << count <<'\n'; X ob(2006); cout << ob.year <<"\n"; return 0; } //------------------------ ////////// OneCount.cpp//////// namespace BitsSpace{ int onePerByte(char x); int oneCount(char *buf,int bytes); // ------------------- int onePerByte(char x) {int count=0,i; for(i=0;i<8;i++) {if(x & '\x1') count++; // 'A'<=> '\x41' x>>=1; //x=x>>1; } return count; } // --- int oneCount(char *buf,int bytes) {int count=0,i; for(i=0;i<bytes;i++) count+=onePerByte(buf[i]); return count; } // --- } ---------------- ////////// testOne.cpp//////// #include <iostream> #include "OneCount.cpp" using namespace std; //using namespace BitsSpace; const int SLen=80; // ---- int main(){ char ms[SLen],*p; cout<<"Enter your words:\n> " ; cin.getline(ms,SLen); cout<< BitsSpace::oneCount(ms,strlen(ms))<<"\n"; cout<<"Size of char: "<<sizeof(char)<<"\n"; return 0; } ========================================= //////////////////////////////// // XVII. C++ file handle, 6 programs // by Hs.li 2007.4.28 //////////////////////////////// // Write text strings! #include <iostream> #include <fstream> using namespace std; #define MaxN 200 // - - - - - - int main() {fstream outF; char text[MaxN]; cout<<"Enter lines, end with empty line:\n"; outF.open("str.txt",ios::out); if(!outF.is_open()) {cout<<"File open failed!\n"; return -1; } while(1) { cin.getline(text,MaxN); if(!text[0])break; outF<<text<<"\n"; if(outF.bad()||outF.fail()) {cout<<"Write file error!\n"; outF.close(); return -2; } } cout<<"Write text file okey!\n"; outF.close(); return 0; } ========================= // Read text strings! #include <iostream> #include <fstream> using namespace std; #define MaxN 200 // - - - - - - int main() {fstream inF; char text[MaxN]; cout<<"The text lines are:\n"; inF.open("str.txt",ios::in); if(!inF.is_open()) {cout<<"File open failed!\n"; return -1; } while(1) { inF.getline(text,MaxN); if(inF.eof()|inF.fail()|inF.bad())break; cout<<text<<"\n"; } if(!inF.eof()) {cout<<"Read file error!\n"; inF.close(); return -2; } cout<<"---- End!\n"; inF.close(); return 0; } ====================== // Write text data! #include <iostream> #include <fstream> using namespace std; // - - - - - - int main() { const int MaxN=8; fstream outF; double a[MaxN]; char *fname="data.txt"; int i; cout<<"Please input 8 double: "; for(i=0;i<MaxN;i++) cin>>a[i]; outF.open(fname,ios::out); if(!outF.is_open()) {cout<<"File open failed!\n"; return -1; } outF.exceptions(fstream::failbit| fstream::badbit); try{ for(i=0;i<MaxN;i++) outF<<a[i]<<" "; } catch(std::exception &e) {cout<<"Exception caught:"<<e.what()<<endl; outF.close(); return -2; } outF.close(); cout<<"Text data file write okey!\n"; return 0; } ============================ // Read text data! #include <iostream> #include <fstream> using namespace std; // - - - - - - int main() { fstream inF; double b; char *fname="data.txt"; cout<<"Please wait for reading data:\n"; inF.open(fname,ios::in); if(!inF.is_open()) {cout<<"File open failed!\n"; return -1; } inF.exceptions(fstream::failbit| fstream::badbit|fstream::eofbit); try{ while(1) { inF>>b; cout<<b<<" "; } }catch(std::exception &e) { if(!inF.eof()) { cout<<"Exception caught:"<<e.what()<<endl; inF.close(); return -2; } } inF.close(); cout<<"\nText data file read okey!\n"; return 0; } =============================== // Write binary data! #include <iostream> #include <fstream> using namespace std; // - - - - - - int main() { const int MaxN=8; fstream outF; double a[MaxN]; char *fname="data.dat"; int i; cout<<"Please input 8 double: "; for(i=0;i<MaxN;i++) cin>>a[i]; outF.open(fname,ios::out|ios::binary); if(!outF.is_open()) {cout<<"File open failed!\n"; return -1; } outF.exceptions(fstream::failbit| fstream::badbit); try{ outF.write((char *)a,MaxN*sizeof(double)); } catch(std::exception &e) {cout<<"Exception caught:"<<e.what()<<endl; outF.close(); return -2; } outF.close(); cout<<"Binary data file write okey!\n"; return 0; } ================================ // Read binary data! #include <iostream> #include <fstream> using namespace std; // - - - - - - int main() { fstream inF; double b; char *fname="data.dat"; cout<<"Please wait for reading data:\n"; inF.open(fname,ios::in|ios::binary); if(!inF.is_open()) {cout<<"File open failed!\n"; return -1; } inF.exceptions(fstream::failbit| fstream::badbit|fstream::eofbit); try{ while(1) { inF.read((char *)&b,sizeof(double)); cout<<b<<" "; } }catch(std::exception &e) { if(!inF.eof()) { cout<<"Exception caught:"<<e.what()<<endl; inF.close(); return -2; } } inF.close(); cout<<"\nBinary data file read okey!\n"; return 0; } ////////////////////////////////////////////////

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值