编译不可通过?short s1 = 1;short s2 = 2;short s3 = s1 + s2; why??

崔鹏飞 2008-08-26 12:48:26
编译不可通过?
short s1 = 1;
short s2 = 2;
short s3 = s1 + s2;
why??
...全文
467 19 打赏 收藏 转发到动态 举报
写回复
用AI写文章
19 条回复
切换为时间正序
请发表友善的回复…
发表回复
崔鹏飞 2008-08-27
  • 打赏
  • 举报
回复
如果两个int相加的话,也有越界的可能啊.....
TorerCoder 2008-08-27
  • 打赏
  • 举报
回复
这个是面试题,我以前就遇到过!呵呵。。。贴到这里了。。。。
LovingAlison 2008-08-27
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 whycom 的回复:]
s1 + s2 结果为int
s3 = (short)(s1+s2);
[/Quote]
崔鹏飞 2008-08-27
  • 打赏
  • 举报
回复
那两个int相加也有可能会溢出啊.......[Quote=引用 10 楼 ojlovecd 的回复:]
引用 3 楼 cuipengfei1 的回复:
s2 s3都是short,两个short相加结果为什么是int?

很简单,比如

C# code
short a = short.MaxValue;
short b = short.MaxValue;
//a+b就会越界
[/Quote]
崔鹏飞 2008-08-27
  • 打赏
  • 举报
回复
[Quote=引用 13 楼 cuipengfei1 的回复:]
那两个int相加也有可能会溢出啊.......[/Quote]
LuckyMouse_ZJU 2008-08-27
  • 打赏
  • 举报
回复
[Quote=引用 17 楼 cuipengfei1 的回复:]
如果两个int相加的话,也有越界的可能啊.....
[/Quote]
int + int 就变成 long 了

你仔细去看看msdn上的隐式类型转换.
liuhz_jsmstc 2008-08-27
  • 打赏
  • 举报
回复
s1+s2的值是int型,而s3是short型,你应该显式转换一下
short s3=(short)(s1+s2);
whycom 2008-08-26
  • 打赏
  • 举报
回复
s1 + s2 结果为int
s3 = (short)(s1+s2);
vwxyzh 2008-08-26
  • 打赏
  • 举报
回复
这个问题涉及cli的定义,
参考:
Common Language Infrastructure (CLI)
Partition III
CIL Instruction Set
Final Draft, Apr 2005
---------------------------------------------------------------------------------
In the following table, “CLI Type” is the type as it is described in metadata. The “Verification Type” is a corresponding type used for type compatibility rules in verification (see §1.8.1.2.2) when considering the types of local variables, arguments, and parameters on methods being called. The column “Verification Type (in stack state)” is used to simulate instructions that load data onto the stack, and shows the types that are actually maintained in the stack state information of the verification algorithm. The column “Managed Pointer to Type” shows the type tracked for managed pointers.

CLI Type Verification Type Verification Type (in stack state) Managed Pointer to Type
int8, unsigned int8, bool int8 int32 int8&
int16, unsigned int16, char int16 int32 int16&
int32, unsigned int32 int32 int32 int32&
int64, unsigned int64 int64 int64 int64&
native int, native unsigned int native int native int native int&
float32 float32 float64 float32&
float64 float64 float64 float64&
Any value type Same type Same type Same type&
Any object type Same type Same type Same type&
Method pointer Same type Same type Not valid


These operate only on integer types. Used for and, div.un, not, or, rem.un, xor. The div.un and rem.un instructions treat their operands as unsigned integers and produce the bit pattern corresponding to the unsigned result. As described in the CLI standard, however, the CLI makes no distinction between signed and unsigned integers on the stack. The not instruction is unary and returns the same type as the input. The shl and shr instructions return the same type as their first operand, and their second operand shall be of type int32 or native int. Boxes marked X indicate invalid CIL sequences. All other boxes denote verifiable combinations of operands.

Table 5: Integer Operations
int32 int64 native int F & O
int32 int32 X native int X X X
int64 X int64 X X X X
native int native int X native int X X X
--------------------------------------------------------------------------------------
注意第一张表的Verification Type (in stack state)列,真正用于计算的是这一列的数据
根据第一张表,所有的byte,sbyte,short,ushort都会被转成int类型进行计算
再根据第二张表,int op(+-*/%) int的结果是int
把int的值赋值给short的变量,自然需要强制转换
rangeon 2008-08-26
  • 打赏
  • 举报
回复
存在从 short 到 int、long、float、double 或 decimal 的预定义隐式转换

不能将存储大小更大的非文本数值类型隐式转换为 short(有关整型的存储大小的信息,请参见 整型表(C# 参考))。例如,请看以下两个 short 变量 x 和 y:

short x = 5, y = 12;


以下赋值语句将产生一个编译错误,原因是赋值运算符右侧的算术表达式在默认情况下的计算结果为 int 类型

short z = x + y; // Error: no conversion from int to short

若要解决此问题,请使用强制转换:

short z = ( short )(x + y); // OK: explicit conversion
西安风影 2008-08-26
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 cuipengfei1 的回复:]
s2 s3都是short,两个short相加结果为什么是int?
[/Quote]

安全考虑
s1s2是short类型,也就是两个字节,如果s1和s2都是两个字节中最大的数
那么s3用short就不能准确表示,所以是int 4个字节来表示
whycom 2008-08-26
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 cuipengfei1 的回复:]
s2 s3都是short,两个short相加结果为什么是int?
[/Quote]
这是编译器决定的,例如你用
short s1;
short s2;
object s3 = s1+ s2;
s3 is int
崔鹏飞 2008-08-26
  • 打赏
  • 举报
回复
s2 s3都是short,两个short相加结果为什么是int?
freewind0521 2008-08-26
  • 打赏
  • 举报
回复
s1 + s2 在运算时会转化为int类型在计算,所以结果也是int类型
崔鹏飞 2008-08-26
  • 打赏
  • 举报
回复
好的,非常感谢
我姓区不姓区 2008-08-26
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 cuipengfei1 的回复:]
s2 s3都是short,两个short相加结果为什么是int?
[/Quote]
很简单,比如

short a = short.MaxValue;
short b = short.MaxValue;
//a+b就会越界
ericzhangbo1982111 2008-08-26
  • 打赏
  • 举报
回复
考试题吧。。。。
貌似在那里见到过

rangeon 2008-08-26
  • 打赏
  • 举报
回复
[Quote=引自MSDN:]
存在从 short 到 int、long、float、double 或 decimal 的预定义隐式转换。

不能将存储大小更大的非文本数值类型隐式转换为 short(有关整型的存储大小的信息,请参见 整型表(C# 参考))。例如,请看以下两个 short 变量 x 和 y:

short x = 5, y = 12;


以下赋值语句将产生一个编译错误,原因是赋值运算符右侧的算术表达式在默认情况下的计算结果为 int 类型。

short z = x + y; // Error: no conversion from int to short

若要解决此问题,请使用强制转换:

short z = ( short )(x + y); // OK: explicit conversion
[/Quote]
jietuan 2008-08-26
  • 打赏
  • 举报
回复
编译器决定的,没有办法,我觉得尽量少用short类型
第 一 章 概述 1-1 简述计算机程序设计语言的发展历程。 解: 迄今为止计算机程序设计语言的发展经历了机器语言、汇编语言、高级语言等阶段,C++语言是一种面向对象的编程语言,也属于高级语言。 1-2 面向对象的编程语言有哪些特点? 解: 面向对象的编程语言与以往各种编程语言有根本的不同,它设计的出发点就是为了能更直接的描述客观世界中存在的事物以及它们之间的关系。面向对象的编程语言将客观事物看作具有属性和行为的对象,通过抽象找出同一类对象的共同属性(静态特征)和行为(动态特征),形成类。通过类的继承与多态可以很方便地实现代码重用,大大缩短了软件开发周期,并使得软件风格统一。因此,面向对象的编程语言使程序能够比较直接地反问题域的本来面目,软件开发人员能够利用人类认识事物所采用的一般思维方法来进行软件开发。C++语言是目前应用最广的面向对象的编程语言。 1-3 什么是结构化程序设计方法?这种方法有哪些优点和缺点? 解: 结构化程序设计的思路是:自顶向下、逐步求精;其程序结构是按功能划分为若干个基本模块;各模块之间的关系尽可能简单,在功能上相对独立;每一模块内部均是由顺序、选择和循环三种基本结构组成;其模块化实现的具体方法是使用子程序。结构化程序设计由于采用了模块分解与功能抽象,自顶向下、分而治之的方法,从而有效地将一个较复杂的程序系统设计任务分解成许多易于控制和处理的子任务,便于开发和维护。 虽然结构化程序设计方法具有很多的优点,但它仍是一种面向过程的程序设计方法,它把数据和处理数据的过程分离为相互独立的实体。当数据结构改变时,所有相关的处理过程都要进行相应的修改,每一种相对于老问题的新方法都要带来额外的开销,程序的可重用性差。 由于图形用户界面的应用,程序运行由顺序运行演变为事件驱动,使得软件使用起来越来越方便,但开发起来却越来越困难,对这种软件的功能很难用过程来描述和实现,使用面向过程的方法来开发和维护都将非常困难。 1-4 什么是对象?什么是面向对象方法?这种方法有哪些特点? 解: 从一般意义上讲,对象是现实世界中一个实际存在的事物,它可以是有形的,也可以是无形的。对象是构成世界的一个独立单位,它具有自己的静态特征和动态特征。面向对象方法中的对象,是系统中用来描述客观事物的一个实体,它是用来构成系统的一个基本单位,由一组属性和一组行为构成。 面向对象的方法将数据及对数据的操作方法放在一起,作为一个相互依存、不可分离的整体--对象。对同类型对象抽象出其共性,形成类。类中的大多数数据,只能用本类的方法进行处理。类通过一个简单的外部接口,与外界发生关系,对象与对象之间通过消息进行通讯。这样,程序模块间的关系更为简单,程序模块的独立性、数据的安全性就有了良好的保障。通过实现继承与多态性,还可以大大提高程序的可重用性,使得软件的开发和维护都更为方便。 面向对象方法所强调的基本原则,就是直接面对客观存在的事物来进行软件开发,将人们在日常生活中习惯的思维方式和表达方式应用在软件开发中,使软件开发从过分专业化的方法、规则和技巧中回到客观世界,回到人们通常的思维。 1-5 什么叫做封装? 解: 封装是面向对象方法的一个重要原则,就是把对象的属性和服务结合成一个独立的系统单位,并尽可能隐蔽对象的内部细节。 1-6 面向对象的软件工程包括哪些主要内容? 解: 面向对象的软件工程是面向对象方法在软件工程领域的全面应用,它包括面向对象的分析(OOA)、面向对象的设计(OOD)、面向对象的编程(OOP)、面向对象的测试(OOT)和面向对象的软件维护(OOSM)等主要内容。 1-7 简述计算机内部的信息可分为几类? 解: 计算机内部的信息可以分成控制信息和数据信息二大类;控制信息可分为指令和控制字两类;数据信息可分为数值信息和非数值信息两类。 1-8 什么叫二进制?使用二进制有何优点和缺点? 解: 二进制是基数为2,每位的权是以2 为底的幂的进制,遵循逢二进一原则,基本符号为0和1。采用二进制码表示信息,有如下几个优点:1.易于物理实现;2.二进制数运算简单;3.机器可靠性高;4.通用性强。其缺点是它表示数的容量较小,表示同一个数,二进制较其他进制需要更多的位数。 1-9 请将以下十进制数值转换为二进制和十六进制补码: (1)2 (2)9 (3)93 (4)-32 (5)65535 (6)-1 解: (1) (2)10 = (10)2 = (2)16 (2) (9)10 = (1001)2 = (9)16 (3) (93)10 = (1011101)2 = (5D)16 (4) (-32)10 = (11100000)2 = (E0)16 (5) (65535)10 = (11111111 11111111)2 = (FFFF)16 (6) (-1)10 = (11111111 11111111)2 = (FFFF)16 1-10 请将以下数值转换为十进制: (1)(1010)2 (2)(10001111)2 (3)(01011111 11000011)2 (4)(7F)16 (5)(2D3E)16 (6)(F10E)16 解: (1)(1010)2 = (10)10 (2)(10001111)2 = (143)10 (3)(01011111 11000011)2 = (24515)10 (4)(7F)16 = (127)10 (5)(2D3E)16 = (11582)10 (6)(F10E)16 = (61710)10 1-11 简要比较原码、反码、补码等几种编码方法。 解: 原码:将符号位数字化为 0 或 1,数的绝对值与符号一起编码,即所谓"符号──绝对值表示"的编码。 正数的反码和补码与原码表示相同。 负数的反码与原码有如下关系: 符号位相同(仍用1表示),其余各位取反(0变1,1变0)。 补码由该数反码的最末位加1求得。 第 二 章 C++简单程序设计 2-1 C++语言有那些主要特点和优点? 解: C++语言的主要特点表现在两个方面,一是全面兼容C,二是支持面向对象的方法。C++是一个更好的C,它保持了C的简洁、高效、接近汇编语言、具有良好的可读性和可移植性等特点,对C的类型系统进行了改革和扩充,因此C++比C更安全,C++的编译系统能检查出更多的类型错误。 C++语言最重要的特点是支持面向对象。 2-2 下列标识符哪些是合法的? Program, -page, _lock, test2, 3in1, @mail, A_B_C_D 解: Program, _lock, test2, A_B_C_D是合法的标识符,其它的不是。 2-3 例2.1中每条语句的作用是什么? #include void main(void) { cout<<"Hello!\n"; cout<<"Welcome to c++!\n"; } 解: #include //指示编译器将文件iostream.h中的代码 //嵌入到该程序中该指令所在的地方 void main() //主函数名,void 表示函数没有返回值 { //函数体标志 cout<<"Hello!\n"; //输出字符串Hello!到标准输出设备(显示器)上。 cout<<"Welcome to c++!\n"; //输出字符串Welcome to c++! } 在屏幕输出如下: Hello! Welcome to c++! 2-4 使用关键字const而不是#define语句的好处有哪些? 解: const定义的常量是有类型的,所以在使用它们时编译器可以查错;而且,这些变量在调试时仍然是可见的。 2-5 请写出C++语句声明一个常量PI,值为3.1416;再声明一个浮点型变量a,把PI的值赋给a。 解: const float PI = 3.1416; float a = PI; 2-6 在下面的枚举类型中,Blue的值是多少? enum COLOR { WHITE, BLACK = 100, RED, BLUE, GREEN = 300 }; 解: Blue = 102 2-7 注释有什么作用?C++中有哪几种注释的方法?他们之间有什么区别? 解: 注释在程序中的作用是对程序进行注解和说明,以便于阅读。编译系统在对源程序进行编译时不理会注释部分,因此注释对于程序的功能实现不起任何作用。而且由于编译时忽略注释部分,所以注释内容不会增加最终产生的可执行程序的大小。适当地使用注释,能够提高程序的可读性。在C++中,有两种给出注释的方法:一种是延用C语言方法,使用"/*"和"*/"括起注释文字。另一种方法是使用"//",从"//"开始,直到它所在行的行尾,所有字符都被作为注释处理。 2-8 什么叫做表达式?x = 5 + 7是一个表达式吗?它的值是多少? 解: 任何一个用于计算值的公式都可称为表达式。x = 5 + 7是一个表达式,它的值为12。 2-9 下列表达式的值是多少? 1. 201 / 4 2. 201 % 4 3. 201 / 4.0 解: 1. 50 2. 1 3. 50.25 2-10 执行完下列语句后,a、b、c三个变量的值为多少? a = 30; b = a++; c = ++a; 解: a:32 ; b:30 ; c:32; 2-11 在一个for循环中,可以初始化多个变量吗?如何实现? 解: 在for循环设置条件的第一个";"前,用,分隔不同的赋值表达式。 例如: for (x = 0, y = 10; x < 100; x++, y++) 2-12 执行完下列语句后,n的值为多少? int n; for (n = 0; n < 100; n++) 解: n的值为100 2-13 写一条for语句,计数条件为n从100到200,步长为2;然后用while和do…while语句完成同样的循环。 解: for循环: for (int n = 100; n <= 200; n += 2); while循环: int x = 100; while (n <= 200) n += 2; do…while循环: int n = 100; do { n += 2; } while(n y) x = y; else // y > x || y == x y = x; 2-17 修改下面这个程序中的错误,改正后它的运行结果是什么? #include void main() int i int j; i = 10; /* 给i赋值 j = 20; /* 给j赋值 */ cout << "i + j = << i + j; /* 输出结果 */ return 0; } 解: 改正: #include int main() { int i; int j; i = 10; // 给i赋值 j = 20; /* 给j赋值 */ cout << "i + j = " << i + j; /* 输出结果 */ return 0; } 程序运行输出: i + j = 30 2-18 编写一个程序,运行时提示输入一个数字,再把这个数字显示出来。 解: 源程序: #include int main() { int i; cout <> i; cout << "您输入一个数字是" << i << endl; return 0; } 程序运行输出: 请输入一个数字:5 您输入一个数字是5 2-19 C++有哪几种数据类型?简述其值域。编程显示你使用的计算机中的各种数据类型的字节数。 解: 源程序: #include int main() { cout << "The size of an int is:\t\t" << sizeof(int) << " bytes.\n"; cout << "The size of a short int is:\t" << sizeof(short) << " bytes.\n"; cout << "The size of a long int is:\t" << sizeof(long) << " bytes.\n"; cout << "The size of a char is:\t\t" << sizeof(char) << " bytes.\n"; cout << "The size of a float is:\t\t" << sizeof(float) << " bytes.\n"; cout << "The size of a double is:\t" << sizeof(double) << " bytes.\n"; return 0; } 程序运行输出: The size of an int is: 4 bytes. The size of a short int is: 2 bytes. The size of a long int is: 4 bytes. The size of a char is: 1 bytes. The size of a float is: 4 bytes. The size of a double is: 8 bytes. 2-20 打印ASCII码为32~127的字符。 解: #include int main() { for (int i = 32; i<128; i++) cout << (char) i; return 0; } 程序运行输出: !"#$%G'()*+,./0123456789:;?@ABCDEFGHIJKLMNOP_QRSTUVWXYZ[\]^'abcdefghijklmnopqrstuvwxyz~s 2-21 运行下面的程序,观察其输出,与你的设想是否相同? #include int main() { unsigned int x; unsigned int y = 100; unsigned int z = 50; x= y - z; cout << "Difference is: " << x; x = z - y; cout << "\nNow difference is: " << x <不可改变的量,除了用文字表示常量外,也可以为常量命名,这就是符号常量;在程序的执行过程中其值可以变化的量称为变量,变量是需要用名字来标识的。 2-24 变量有哪几种存储类型? 解: 变量有以下几种存储类型: auto存储类型:采用堆栈方式分配内存空间,属于一时性存储,其存储空间可以被若干变量多次覆盖使用; register存储类型:存放在通用寄存器中; extern存储类型:在所有函数和程序段中都可引用; static存储类型:在内存中是以固定地址存放的,在整个程序运行期间都有效。 2-25 写出下列表达式的值: 1. 2 < 3 && 6 < 9 2. ! ( 4 5) || (6 > 2 解: 1. 1 2. -1 3. 0 4. 0 2-28 编写一个完整的程序,实现功能:向用户提问"现在正在下雨吗?",提示用户输入Y或N。若输入为Y,显示"现在正在下雨。"; 若输入为N,显示"现在没有下雨。";否则继续提问"现在正在下雨吗?" 解: 源程序: #include #include void main() { char flag; while(1) { cout <> flag; if ( toupper(flag) == 'Y') { cout << "现在正在下雨。"; break; } if ( toupper(flag) == 'N') { cout << "现在没有下雨。"; break; } } } 程序运行输出: 现在正在下雨吗?(Yes or No):x 现在正在下雨吗?(Yes or No):l 现在正在下雨吗?(Yes or No):q 现在正在下雨吗?(Yes or No):n 现在没有下雨。 或: 现在正在下雨吗?(Yes or No):y 现在正在下雨。 2-29 编写一个完整的程序,运行时向用户提问"你考试考了多少分?(0~100)",接收输入后判断其等级,显示出来。规则如下: 解: #include void main() { int i,score; cout <> score; if (score>100 || score<0) cout << "分数值必须在0到100之间!"; else { i = score/10; switch (i) { case 10: case 9: cout << "你的成绩为优!"; break; case 8: cout << "你的成绩为良!"; break; case 7: case 6: cout << "你的成绩为中!"; break; default: cout << "你的成绩为差!"; } } } 程序运行输出: 你考试考了多少分?(0~100):85 你的成绩为良! 2-30 (1)实现一个简单的菜单程序,运行时显示"Menu: A(dd) D(elete) S(ort) Q(uit), Select one:"提示用户输入,A表示增加,D表示删除,S表示排序,Q表示退出,输入为A、D、S时分别提示"数据已经增加、删除、排序。"输入为Q时程序结束。要求使用if … else语句进行判断,用break、continue控制程序流程。 解: #include #include void main() { char choice,c; while(1) { cout <> c; choice = toupper(c); if (choice == 'A') { cout << "数据已经增加. " << endl; continue; } else if (choice == 'D') { cout << "数据已经删除. " << endl; continue; } else if (choice == 'S') { cout << "数据已经排序. " << endl; continue; } else if (choice == 'Q') break; } } 程序运行输出: Menu: A(dd) D(elete) S(ort) Q(uit), Select one:a 数据已经增加. Menu: A(dd) D(elete) S(ort) Q(uit), Select one:d 数据已经删除. Menu: A(dd) D(elete) S(ort) Q(uit), Select one:s 数据已经排序. Menu: A(dd) D(elete) S(ort) Q(uit), Select one:q (2)实现一个简单的菜单程序,运行时显示"Menu: A(dd) D(elete) S(ort) Q(uit), Select one:"提示用户输入,A表示增加,D表示删除,S表示排序,Q表示退出,输入为A、D、S时分别提示"数据已经增加、删除、排序。"输入为Q时程序结束。要求使用Switch语句。 解: 源程序: #include #include void main() { char choice; while(1) { cout <> choice; switch(toupper(choice)) { case 'A': cout << "数据已经增加. " << endl; break; case 'D': cout << "数据已经删除. " << endl; break; case 'S': cout << "数据已经排序. " << endl; break; case 'Q': exit(0); break; default: ; } } } 程序运行输出: Menu: A(dd) D(elete) S(ort) Q(uit), Select one:a 数据已经增加. Menu: A(dd) D(elete) S(ort) Q(uit), Select one:d 数据已经删除. Menu: A(dd) D(elete) S(ort) Q(uit), Select one:s 数据已经排序. Menu: A(dd) D(elete) S(ort) Q(uit), Select one:q 2-31 用穷举法找出1~100间的质数,显示出来。分别使用while,do-while,for循环语句实现。 解: 源程序: 使用while循环语句: #include #include void main() { int i,j,k,flag; i = 2; while(i <= 100) { flag = 1; k = sqrt(i); j = 2; while (j <= k) { if(i%j == 0) { flag = 0; break; } j++; } if (flag) cout << i << "是质数." << endl; i++; } } 使用do…while循环语句: #include #include void main() { int i,j,k,flag; i = 2; do{ flag = 1; k = sqrt(i); j = 2; do{ if(i%j == 0) { flag = 0; break; } j++; }while (j <= k); if (flag) cout << i << "是质数." << endl; i++; }while(i <= 100); } 使用for循环语句: #include #include void main() { int i,j,k,flag; for(i = 2; i <= 100; i++) { flag = 1; k = sqrt(i); for (j = 2; j <= k; j++) { if(i%j == 0) { flag = 0; break; } } if (flag) cout << i << "是质数." << endl; } } 程序运行输出: 2是质数. 3是质数. 5是质数. 7是质数. 11是质数. 13是质数. 17是质数. 19是质数. 23是质数. 29是质数. 31是质数. 37是质数. 41是质数. 43是质数. 47是质数. 53是质数. 59是质数. 61是质数. 67是质数. 71是质数. 73是质数. 79是质数. 83是质数. 89是质数. 97是质数. 2-32 比较Break语句与Continue语句的不同用法。 解: Break使程序从循环体和switch语句内跳出,继续执行逻辑上的下一条语句,不能用在别处; continue 语句结束本次循环,接着开始判断决定是否继续执行下一次循环; 2-33 定义一个表示时间的结构体,可以精确表示年、月、日、小时、分、秒;提示用户输入年、月、日、小时、分、秒的值,然后完整地显示出来。 解: 源程序见"实验指导"部分实验二 2-34 在程序中定义一个整型变量,赋以1~100的值,要求用户猜这个数,比较两个数的大小,把结果提示给用户,直到猜对为止。分别使用while、do…while语句实现循环。 解: //使用while语句 #include void main() { int n = 18; int m = 0; while(m != n) { cout <> m; if (n > m) cout << "你猜的值太小了!" << endl; else if (n < m) cout << "你猜的值太大了!" << endl; else cout << "你猜对了!" << endl; } } //使用do…while语句 #include void main() { int n = 18; int m = 0; do{ cout <> m; if (n > m) cout << "你猜的值太小了!" << endl; else if (n < m) cout << "你猜的值太大了!" << endl; else cout << "你猜对了!" << endl; }while(n != m); } 程序运行输出: 请猜这个数的值为多少?(0~~100):50 你猜的值太大了! 请猜这个数的值为多少?(0~~100):25 你猜的值太大了! 请猜这个数的值为多少?(0~~100):10 你猜的值太小了! 请猜这个数的值为多少?(0~~100):15 你猜的值太小了! 请猜这个数的值为多少?(0~~100):18 你猜对了! 2-35 定义枚举类型weekday,包括Sunday到Saturday七个元素在程序中定义weekday类型的变量,对其赋值,定义整型变量,看看能否对其赋weekday类型的值。 解: #include enum weekday { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }; void main() { int i; weekday d = Thursday; cout << "d = " << d << endl; i = d; cout << "i = " << i << endl; d = (weekday)6; cout << "d = " << d << endl; d = weekday( 4 ); cout << "d = " << d << endl; } 程序运行输出: d = 4 i = 4 d = 6 d = 4 2-36口袋中有红、黄、蓝、白、黑五种颜色的球若干个,每次从口袋中取出三个不同颜色的球,问有多少种取法。 解: #include using namespace std; int main() { enum color{red,yellow,blue,white,black}; enum color pri; int n,loop,i,j,k; char c; n=0; for(i=red;i<=black;i++) for(j=red;j<=black;j++) if(i!=j) { for(k=red;k编译器在编译时在调用处用函数体进行替换,节省了参数传递、控制转移等开销; 内联函数体内不能有循环语句和switch语句; 内联函数的定义必须出现在内联函数第一次被调用之前; 对内联函数不能进行异常接口声明; 3-5 函数原型中的参数名与函数定义中的参数名以及函数调用中的参数名必须一致吗? 解: 不必一致,所有的参数是根据位置和类型而不是名字来区分的。 3-6 重载函数时通过什么来区分? 解: 重载的函数的函数名是相同的,但它们的参数的个数和数据类型不同,编译器根据实参和形参的类型及个数的最佳匹配,自动确定调用哪一个函数。 3-7 编写函数,参数为两个unsigned short int型数,返回值为第一个参数除以第二个参数的结果,数据类型为short int;如果第二个参数为0,则返回值为-1。在主程序中实现输入输出。 解: 源程序: #include short int Divider(unsigned short int a, unsigned short int b) { if (b == 0) return -1; else return a/b; } typedef unsigned short int USHORT; typedef unsigned long int ULONG; int main() { USHORT one, two; short int answer; cout <> one; cout <> two; answer = Divider(one, two); if (answer > -1) cout << "Answer: " << answer; else cout << "Error, can't divide by zero!"; return 0; } 程序运行输出: Enter two numbers. Number one:8 Number two:2 Answer: 4 3-8 编写函数把华氏温度转换为摄氏温度,公式为:C = (F - 32) * 5/9; 在主程序中提示用户输入一个华氏温度,转化后输出相应的摄氏温度。 解: 源程序见"实验指导"部分实验三 3-9 编写函数判断一个数是否是质数,在主程序中实现输入、输出。 解: #include #include int prime(int i); //判一个数是否是质数的函数 void main() { int i; cout <> i; if (prime(i)) cout << i << "是质数." << endl; else cout << i << "不是质数." << endl; } int prime(int i) { int j,k,flag; flag = 1; k = sqrt(i); for (j = 2; j <= k; j++) { if(i%j == 0) { flag = 0; break; } } if (flag) return 1; else return 0; } 程序运行输出: 请输入一个整数:1151 1151是质数. 3-10 编写函数求两个整数的最大公约数和最小公倍数。 解: 源程序: #include #include int fn1(int i,int j); //求最大公约数的函数 void main() { int i,j,x,y; cout <> i ; cout <> j ; x = fn1(i,j); y = i * j / x; cout << i << "和" << j << "的最大公约数是:" << x << endl; cout << i << "和" << j << "的最小公倍数是:" << y << endl; } int fn1(int i, int j) { int temp; if (i < j) { temp = i; i = j; j = i; } while(j != 0) { temp = i % j; i = j; j = temp; } return i; } 程序运行输出: 请输入一个正整数:120 请输入另一个正整数:72 120和72的最大公约数是:24 120和72的最小公倍数是:360 3-11 什么叫作嵌套调用?什么叫作递归调用? 解: 函数允许嵌套调用,如果函数1调用了函数2,函数2再调用函数3,便形成了函数的嵌套调用。 函数可以直接或间接地调用自身,称为递归调用。 3-12 在主程序中提示输入整数n,编写函数用递归的方法求1 + 2 + … + n的值。 解: #include #include int fn1(int i); void main() { int i; cout <> i ; cout << "从1累加到" < number; cout <> power; answer = GetPower(number,power); cout << number << " to the " << power << "th power is " < n; cout <> x; cout << "n = " << n << endl; cout << "x = " << x << endl; cout << "P" << n << "(" << x << ") = " << p(n,x) << endl; } float p(int n, int x) { if (n == 0) return 1; else if (n == 1) return x; else return ((2*n-1)*x*p(n-1,x) - (n-1)*p(n-2,x)) /n ; } 程序运行输出: 请输入正整数n:1 请输入正整数x:2 n = 1 x = 2 P1(2) = 2 请输入正整数n:3 请输入正整数x:4 n = 3 x = 4 P3(4) = 154 第 四 章 类 4-1 解释public和private的作用,公有类型成员与私有类型成员有些什么区别? 解: 公有类型成员用public关键字声明,公有类型定义了类的外部接口;私有类型的成员用private关键字声明,只允许本类的函数成员来访问,而类外部的任何访问都是非法的,这样,私有的成员就整个隐蔽在类中,在类的外部根本就无法看到,实现了访问权限的有效控制。 4-2 protected关键字有何作用? 解: protected用来声明保护类型的成员,保护类型的性质和私有类型的性质相似,其差别在于继承和派生时派生类的成员函数可以访问基类的保护成员。 4-3 构造函数和析构函数有什么作用? 解: 构造函数的作用就是在对象被创建时利用特定的值构造对象,将对象初始化为一个特定的状态,使此对象具有区别于彼对象的特征,完成的就是是一个从一般到具体的过程,构造函数在对象创建的时候由系统自动调用。 析构函数与构造函数的作用几乎正好相反,它是用来完成对象被删除前的一些清理工作,也就是专门作扫尾工作的。一般情况下,析构函数是在对象的生存期即将结束的时刻由系统自动调用的,它的调用完成之后,对象也就消失了,相应的内存空间也被释放。 4-4 数据成员可以为公有的吗?成员函数可以为私有的吗? 解: 可以,二者都是合法的。数据成员和成员函数都可以为公有或私有的。但数据成员最好定义为私有的。 4-5 已知class A中有数据成员int a,如果定义了A的两个对象A1、A2,它们各自的数据成员a的值可以不同吗? 解: 可以,类的每一个对象都有自己的数据成员。 4-6 什么叫做拷贝构造函数?拷贝构造函数何时被调用? 解: 拷贝构造函数是一种特殊的构造函数,具有一般构造函数的所有特性,其形参是本类的对象的引用,其作用是使用一个已经存在的对象,去初始化一个新的同类的对象。在以下三种情况下会被调用:在当用类的一个对象去初始化该类的另一个对象时;如果函数的形参是类对象,调用函数进行形参和实参结合时;如果函数的返回值是类对象,函数调用完成返回时; 4-7 拷贝构造函数与赋值运算符(=)有何不同? 解: 赋值运算符(=)作用于一个已存在的对象;而拷贝构造函数会创建一个新的对象。 4-8 定义一个Dog 类,包含的age、weight等属性,以及对这些属性操作的方法。实现并测试这个类。 解: 源程序: #include class Dog { public: Dog (int initialAge = 0, int initialWeight = 5); ~Dog(); int GetAge() { return itsAge;} // inline! void SetAge (int age) { itsAge = age;} // inline! int GetWeight() { return itsWeight;} // inline! void SetWeight (int weight) { itsAge = weight;} // inline! private: int itsAge, itsWeight; }; Dog::Dog(int initialAge, int initialWeight) { itsAge = initialAge; itsWeight = initialWeight; } Dog::~Dog() //destructor, takes no action { } int main() { Dog Jack(2,10); cout << "Jack is a Dog who is " ; cout << Jack.GetAge() << " years old and"; cout << Jack.GetWeight() << " pounds weight.\n"; Jack.SetAge(7); Jack.SetWeight(20); cout << "Now Jack is " ; cout << Jack.GetAge() << " years old and"; cout << Jack.GetWeight() << " pounds weight."; return 0; } 程序运行输出: Jack is a Dog who is 2 years old and 10 pounds weight. Now Jack is 7 years old 20 pounds weight. 4-9 设计并测试一个名为Rectangle的矩形类,其属性为矩形的左下角与右上角两个点的坐标,能计算矩形的面积。 解: 源程序: #include class Rectangle { public: Rectangle (int top, int left, int bottom, int right); ~Rectangle () {} int GetTop() const { return itsTop; } int GetLeft() const { return itsLeft; } int GetBottom() const { return itsBottom; } int GetRight() const { return itsRight; } void SetTop(int top) { itsTop = top; } void SetLeft (int left) { itsLeft = left; } void SetBottom (int bottom) { itsBottom = bottom; } void SetRight (int right) { itsRight = right; } int GetArea() const; private: int itsTop; int itsLeft; int itsBottom; int itsRight; }; Rectangle::Rectangle(int top, int left, int bottom, int right) { itsTop = top; itsLeft = left; itsBottom = bottom; itsRight = right; } int Rectangle::GetArea() const { int Width = itsRight-itsLeft; int Height = itsTop - itsBottom; return (Width * Height); } int main() { Rectangle MyRectangle (100, 20, 50, 80 ); int Area = MyRectangle.GetArea(); cout << "Area: " << Area << "\n"; return 0; } 程序运行输出: Area: 3000 Upper Left X Coordinate: 20 4-10 设计一个用于人事管理的People(人员)类。考虑到通用性,这里只抽象出所有类型人员都具有的属性:number(编号)、sex(性别)、birthday(出生日期)、id(身份证号)等等。其中"出生日期"定义为一个"日期"类内嵌子对象。用成员函数实现对人员信息的录入和显示。要求包括:构造函数和析构函数、拷贝构造函数、内联成员函数、带缺省形参值的成员函数、聚集。 解: 本题用作实验四的选做题,因此不给出答案。 4-11 定义一个矩形类,有长、宽两个属性,有成员函数计算矩形的面积 解: #include class Rectangle { public: Rectangle(float len, float width) { Length = len; Width = width; } ~Rectangle(){}; float GetArea() { return Length * Width; } float GetLength() { return Length; } float GetWidth() { return Width; } private: float Length; float Width; }; void main() { float length, width; cout <> length; cout <> width; Rectangle r(length, width); cout << "长为" << length << "宽为" << width << "的矩形的面积为:" << r.GetArea () << endl; } 程序运行输出: 请输入矩形的长度:5 请输入矩形的宽度:4 长为5宽为4的矩形的面积为:20 4-12 定义一个"数据类型" datatype类,能处理包含字符型、整型、浮点型三种类型的数据,给出其构造函数。 解: #include class datatype{ enum{ character, integer, floating_point } vartype; union { char c; int i; float f; }; public: datatype(char ch) { vartype = character; c = ch; } datatype(int ii) { vartype = integer; i = ii; } datatype(float ff) { vartype = floating_point; f = ff; } void print(); }; void datatype::print() { switch (vartype) { case character: cout << "字符型: " << c << endl; break; case integer: cout << "整型: " << i << endl; break; case floating_point: cout << "浮点型: " << f << endl; break; } } void main() { datatype A('c'), B(12), C(1.44F); A.print(); B.print(); C.print(); } 程序运行输出: 字符型: c 整型: 12 浮点型: 1.44 4-13 定义一个Circle类,有数据成员半径Radius,成员函数GetArea(),计算圆的面积,构造一个Circle的对象进行测试。 解: #include class Circle { public: Circle(float radius){ Radius = radius;} ~Circle(){} float GetArea() { return 3.14 * Radius * Radius; } private: float Radius; }; void main() { float radius; cout <> radius; Circle p(radius); cout << "半径为" << radius << "的圆的面积为:" << p.GetArea () << endl; } 程序运行输出: 请输入圆的半径:5 半径为5的圆的面积为:78.5 4-14 定义一个tree类,有成员ages,成员函数grow(int years)对ages加上years,age()显示tree对象的ages的值。 解: #include class Tree { int ages; public: Tree(int n=0); ~Tree(); void grow(int years); void age(); }; Tree::Tree(int n) { ages = n; } Tree::~Tree() { age(); } void Tree::grow(int years) { ages += years; } void Tree::age() { cout << "这棵树的年龄为" << ages << endl; } void main() { Tree t(12); t.age(); t.grow(4); } 程序运行输出: 这棵树的年龄为12 这棵树的年龄为16 第 五 章 C++程序的基本结构 5-1 什么叫做作用域?有哪几种类型的作用域? 解: 作用域讨论的是标识符的有效范围,作用域是一个标识符在程序正文中有效的区域。C++的作用域分为函数原形作用域、块作用域(局部作用域)、类作用域和文件作用域. 5-2 什么叫做可见性?可见性的一般规则是什么? 解: 可见性是标识符是否可以引用的问题; 可见性的一般规则是:标识符要声明在前,引用在后,在同一作用域中,不能声明同名的标识符。对于在不同的作用域声明的标识符,遵循的原则是:若有两个或多个具有包含关系的作用域,外层声明的标识符如果在内层没有声明同名标识符时仍可见,如果内层声明了同名标识符则外层标识符不可见。 5-3 下面的程序的运行结果是什么,实际运行一下,看看与你的设想有何不同。 #include void myFunction(); int x = 5, y = 7; int main() { cout << "x from main: " << x << "\n"; cout << "y from main: " << y << "\n\n"; myFunction(); cout << "Back from myFunction!\n\n"; cout << "x from main: " << x << "\n"; cout << "y from main: " << y << "\n"; return 0; } void myFunction() { int y = 10; cout << "x from myFunction: " << x << "\n"; cout << "y from myFunction: " << y << "\n\n"; } 解: 程序运行输出: x from main: 5 y from main: 7 x from myFunction: 5 y from myFunction: 10 Back from myFunction! x from main: 5 y from main: 7 5-4 假设有两个无关系的类Engine和Fuel,使用时,怎样允许Fuel成员访问Engine中的私有和保护的成员? 解: 源程序: class fuel; class engine { friend class fuel; private; int powerlevel; public; engine(){ powerLevel = 0;} void engine_fn(fuel &f); }; class fuel { friend class engine; private; int fuelLevel; public: fuel(){ fuelLevel = 0;} void fuel_fn( engine &e); }; 5-5 什么叫做静态数据成员?它有何特点? 解: 类的静态数据成员是类的数据成员的一种特例,采用static关键字来声明。对于类的普通数据成员,每一个类的对象都拥有一个拷贝,就是说每个对象的同名数据成员可以分别存储不同的数值,这也是保证对象拥有自身区别于其它对象的特征的需要,但是静态数据成员,每个类只要一个拷贝,由所有该类的对象共同维护和使用,这个共同维护、使用也就实现了同一类的不同对象之间的数据共享。 5-6 什么叫做静态函数成员?它有何特点? 解: 使用static关键字声明的函数成员是静态的,静态函数成员属于整个类,同一个类的所有对象共同维护,为这些对象所共享。静态函数成员具有以下两个方面的好处,一是由于静态成员函数只能直接访问同一个类的静态数据成员,可以保证不会对该类的其余数据成员造成负面影响;二是同一个类只维护一个静态函数成员的拷贝,节约了系统的开销,提高程序的运行效率。 5-7 定义一个Cat类,拥有静态数据成员HowManyCats,记录Cat的个体数目;静态成员函数GetHowMany(),存取HowManyCats。设计程序测试这个类,体会静态数据成员和静态成员函数的用法。 解: 源程序: #include class Cat { public: Cat(int age):itsAge(age){HowManyCats++; } virtual ~Cat() { HowManyCats--; } virtual int GetAge() { return itsAge; } virtual void SetAge(int age) { itsAge = age; } static int GetHowMany() { return HowManyCats; } private: int itsAge; static int HowManyCats; }; int Cat::HowManyCats = 0; void TelepathicFunction(); int main() { const int MaxCats = 5; Cat *CatHouse[MaxCats]; int i; for (i = 0; ii ++; } class Z { public: void f(X* x) { x->i += 5; } }; #endif // MY_X_Y_Z_H 程序运行输出:无 5-14 定义Boat与Car两个类,二者都有weight属性,定义二者的一个友元函数totalWeight(),计算二者的重量和。 解: 源程序: #include class Boat; class Car { private: int weight; public: Car(int j){weight = j;} friend int totalWeight(Car &aCar;, Boat &aBoat;); }; class Boat { private: int weight; public: Boat(int j){weight = j;} friend int totalWeight(Car &aCar;, Boat &aBoat;); }; int totalWeight(Car &aCar;, Boat &aBoat;) { return aCar.weight + aBoat.weight; } void main() { Car c1(4); Boat b1(5); cout << totalWeight(c1, b1) << endl; } 程序运行输出: 9 第 六 章 数组、指针与字符串 6-1 数组A[10][5][15]一共有多少个元素? 解: 10×5×15 = 750 个元素 6-2 在数组A[20]中第一个元素和最后一个元素是哪一个? 解: 第一个元素是A[0],最后一个元素是A[19]。 6-3 用一条语句定义一个有五个元素的整型数组,并依次赋予1~5的初值。 解: 源程序: int IntegerArray[5] = { 1, 2, 3, 4, 5 }; 或:int IntegerArray[] = { 1, 2, 3, 4, 5 }; 6-4 已知有一个数组名叫oneArray,用一条语句求出其元素的个数。 解: 源程序: nArrayLength = sizeof(oneArray) / sizeof(oneArray[0]); 6-5 用一条语句定义一个有5×3个元素的二维整型数组,并依次赋予1~15的初值。 解: 源程序: int theArray[5][3] = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 }; 或:int theArray[5][3] = { {1,2,3}, {4,5,6}, {7,8,9}, {10,11,12},{13,14,15} }; 6-6 运算符*和&的作用是什么? 解: *称为指针运算符,是一个一元操作符,表示指针所指向的对象的值;&称为取地址运算符,也是一个一元操作符,是用来得到一个对象的地址。 6-7 什么叫做指针?指针中储存的地址和这个地址中的值有何区别? 解: 指针是一种数据类型,具有指针类型的变量称为指针变量。指针变量存放的是另外一个对象的地址,这个地址中的值就是另一个对象的内容。 6-8 定义一个整型指针,用new语句为其分配包含10个整型元素的地址空间。 解: 源程序: int *pInteger = new int[10]; 6-9 在字符串”Hello,world!”中结束符是什么? 解: 是NULL字符。 6-10 定义一个有五个元素的整型数组,在程序中提示用户输入元素值,最后再在屏幕上显示出来。 解: 源程序: #include int main() { int myArray[5]; int i; for ( i=0; i<5; i++) { cout << "Value for myArray[" << i <> myArray[i]; } for (i = 0; i<5; i++) cout << i << ": " << myArray[i] << "\n"; return 0; } 程序运行输出: Value for myArray[0]: 2 Value for myArray[1]: 5 Value for myArray[2]: 7 Value for myArray[3]: 8 Value for myArray[4]: 3 0: 2 1: 5 2: 7 3: 8 4: 3 6-11 引用和指针有何区别?何时只能使用指针而不能使用引用? 解: 引用是一个别名,不能为NULL值,不能被重新分配;指针是一个存放地址的变量。当需要对变量重新赋以另外的地址或赋值为NULL时只能使用指针。 6-12 声明下列指针:float类型变量的指针pFloat,char类型的指针pString和struct customer型的指针prec。 解: float *pfloat; char *pString; struct customer *prec; 6-13 给定float类型的指针fp,写出显示fp所指向的值的输出流语句。 解: cout << "Value == " << *fp; 6-14 程序中定义一个double类型变量的指针。分别显示指针占了多少字节和指针所指的变量占了多少字节。 解: double *counter; cout << "\nSize of pointer == "sizeof(counter); cout << '\nSize of addressed value == "<='a' && str[i]='A' && str[i]<='Z') ) num++; } return num; } void main() { char text[100]; cout << "输入一个英语句子:" << endl; gets(text); cout << "这个句子里有" << count(text) << "个字母。" << endl; } 程序运行输出: 输入一个英语句子: It is very interesting! 这个句子里有19个字母。 6-22 编写函数int index(char *s, char *t),返回字符串t 在字符串s中出现的最左边的位置,如果在s中没有与t匹配的子串,就返回-1。 解: 源程序: #include int index( char *s, char *t) { int i,j,k; for(i = 0; s[i] != '\0'; i++) { for(j = i, k = 0; t[k] != '\0' && s[j] == t[k]; j++, k++) ; if (t[k] =='\0') return i; } return -1; } void main() { int n; char str1[20],str2[20]; cout <> str1; cout <> str2; n = index(str1,str2); if (n > 0) cout << str2 << "在" << str1 << "中左起第" << n+1 << "个位置。"< str1; cout << "原字符串为:" << str1 << endl; reverse(str1); cout << "倒序反转后为:" << str1 << endl; } 程序运行输出: 输入一个字符串:abcdefghijk 原字符串为:abcdefghijk 倒序反转后为:kjihgfedcba 6-24 设学生人数N=8,提示用户输入N个人的考试成绩,然后计算出平均成绩,显示出来。 解: 源程序: #include #include #define N 8 float grades[N]; //存放成绩的数组 void main() { int i; float total,average; //提示输入成绩 for(i = 0; i < N; i++ ) { cout << "Enter grade #" <<(i +1) <> grades[i]; } total = 0; for (i = 0; i < N; i++) total += grades[i]; average = total / N; cout << "\nAverage grade: " << average << endl; } 程序运行输出: Enter grade #1: 86 Enter grade #2: 98 Enter grade #3: 67 Enter grade #4: 80 Enter grade #5: 78 Enter grade #6: 95 Enter grade #7: 78 Enter grade #8: 56 Average grade: 79.75 6-25 设计一个字符串类MyString,具有构造函数、析构函数、拷贝构造函数,重载运算符+、=、+=、[],尽可能地完善它,使之能满足各种需要。(运算符重载功能为选做,参见第8章) 解: #include #include class MyString { public: MyString(); MyString(const char *const); MyString(const MyString &); ~MyString(); char & operator[](unsigned short offset); char operator[](unsigned short offset) const; MyString operator+(const MyString&); void operator+=(const MyString&); MyString & operator= (const MyString &); unsigned short GetLen()const { return itsLen; } const char * GetMyString() const { return itsMyString; } private: MyString (unsigned short); // private constructor char * itsMyString; unsigned short itsLen; }; MyString::MyString() { itsMyString = new char[1]; itsMyString[0] = '\0'; itsLen=0; } MyString::MyString(unsigned short len) { itsMyString = new char[len+1]; for (unsigned short i = 0; i<=len; i++) itsMyString[i] = '\0'; itsLen=len; } MyString::MyString(const char * const cMyString) { itsLen = strlen(cMyString); itsMyString = new char[itsLen+1]; for (unsigned short i = 0; ishort i = 0; ishort i = 0; i itsLen) return itsMyString[itsLen-1]; else return itsMyString[offset]; } char MyString::operator[](unsigned short offset) const { if (offset > itsLen) return itsMyString[itsLen-1]; else return itsMyString[offset]; } MyString MyString::operator+(const MyString& rhs) { unsigned short totalLen = itsLen + rhs.GetLen(); MyString temp(totalLen); for (unsigned short i = 0; ishort j = 0; jshort rhsLen = rhs.GetLen(); unsigned short totalLen = itsLen + rhsLen; MyString temp(totalLen); for (unsigned short i = 0; ishort j = 0; js1("initial test"); cout << "S1:\t" << s1.GetMyString() << endl; char * temp = "Hello World"; s1 = temp; cout << "S1:\t" << s1.GetMyString() << endl; char tempTwo[20]; strcpy(tempTwo,"; nice to be here!"); s1 += tempTwo; cout << "tempTwo:\t" << tempTwo << endl; cout << "S1:\t" << s1.GetMyString() << endl; cout << "S1[4]:\t" << s1[4] << endl; s1[4]='x'; cout << "S1:\t" << s1.GetMyString() << endl; cout << "S1[999]:\t" << s1[999] << endl; MyString s2(" Another myString"); MyString s3; s3 = s1+s2; cout << "S3:\t" << s3.GetMyString() << endl; MyString s4; s4 = "Why does this work?"; cout << "S4:\t" << s4.GetMyString() << endl; return 0; } 程序运行输出: S1: initial test S1: Hello World tempTwo: ; nice to be here! S1: Hello World; nice to be here! S1[4]: o S1: Hellx World; nice to be here! S1[999]: ! S3: Hellx World; nice to be here! Another myString S4: Why does this work? 6-26 编写一个3×3矩阵转置的函数,在main()函数中输入数据。 解: #include void move (int matrix[3][3]) { int i, j, k; for(i=0; i<3; i++) for (j=0; j data[i][j]; } cout << "输入的矩阵的为:" << endl; for(i=0; i<3; i++) { for (j=0; j<3; j++) cout << data[i][j] << " "; cout << endl; } move(data); cout << "转置后的矩阵的为:" << endl; for(i=0; i<3; i++) { for (j=0; j<3; j++) cout << data[i][j] << " "; cout << endl; } } 程序运行输出: 输入矩阵的元素 第1行第1个元素为:1 第1行第2个元素为:2 第1行第3个元素为:3 第2行第1个元素为:4 第2行第2个元素为:5 第2行第3个元素为:6 第3行第1个元素为:7 第3行第2个元素为:8 第3行第3个元素为:9 输入的矩阵的为: 1 2 3 4 5 6 7 8 9 转置后的矩阵的为: 1 4 7 2 5 8 3 6 9 6-27 编写一个矩阵转置的函数,矩阵的维数在程序中由用户输入。 解: #include void move (int *matrix ,int n) { int i, j, k; for(i=0; i n; p = new int[n*n]; cout << "输入矩阵的元素" << endl; for(i=0; i p[i*n + j]; } cout << "输入的矩阵的为:" << endl; for(i=0; i不可访问。 私有继承,使得基类public(公有)和protected(保护)成员都以private(私有)成员身份出现在派生类中,而基类private(私有)成员不可访问。 保护继承中,基类public(公有)和protected(保护)成员都以protected(保护)成员身份出现在派生类中,而基类private(私有)成员不可访问。 7-2 派生类构造函数执行的次序是怎样的? 解: 派生类构造函数执行的一般次序为:调用基类构造函数;调用成员对象的构造函数;派生类的构造函数体中的内容。 7-3 如果在派生类B已经重载了基类A的一个成员函数fn1(),没有重载成员函数fn2(),如何调用基类的成员函数fn1()、fn2()? 解: 调用方法为: A::fn1(); fn2(); 7-4 什么叫做虚基类?有何作用? 解: 当某类的部分或全部直接基类是从另一个基类派生而来,这些直接基类中,从上一级基类继承来的成员就拥有相同的名称,派生类的对象的这些同名成员在内存中同时拥有多个拷贝,我们可以使用作用域分辨符来唯一标识并分别访问它们。我们也可以将直接基类的共同基类设置为虚基类,这时从不同的路径继承过来的该类成员在内存中只拥有一个拷贝,这样就解决了同名成员的唯一标识问题。 虚基类的声明是在派生类的定义过程,其语法格式为: class 派生类名:virtual 继承方式 基类名 上述语句声明基类为派生类的虚基类,在多继承情况下,虚基类关键字的作用范围和继承方式关键字相同,只对紧跟其后的基类起作用。声明了虚基类之后,虚基类的成员在进一步派生过程中,和派生类一起维护一个内存数据拷贝。 7-5 定义一个Shape基类,在此基础上派生出Rectangle和Circle,二者都有GetArea()函数计算对象的面积。使用Rectangle类创建一个派生类Square。 解: 源程序: #include class Shape { public: Shape(){} ~Shape(){} virtual float GetArea() { return -1; } }; class Circle : public Shape { public: Circle(float radius):itsRadius(radius){} ~Circle(){} float GetArea() { return 3.14 * itsRadius * itsRadius; } private: float itsRadius; }; class Rectangle : public Shape { public: Rectangle(float len, float width): itsLength(len), itsWidth(width){}; ~Rectangle(){}; virtual float GetArea() { return itsLength * itsWidth; } virtual float GetLength() { return itsLength; } virtual float GetWidth() { return itsWidth; } private: float itsWidth; float itsLength; }; class Square : public Rectangle { public: Square(float len); ~Square(){} }; Square::Square(float len): Rectangle(len,len) { } void main() { Shape * sp; sp = new Circle(5); cout << "The area of the Circle is "

110,533

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧