c++学习笔记

66 阅读16分钟

1.静态强制转化 static_cast(total) explicit conversion

int total=10;

double a=static_cast(total); cout<< static_cast(total);

2.promotion :a=a+10 a is double ,10 is int,int promote into double.

3.setprecision() 设置精度 ,属于库

 Fixed使用一般方式输出浮点数,而不使用科学计数法   粘性设置 sticky setting

 

cout<<fixed<<setprecision( );会约束之后的所有输出,除非再次设置

 Showpoint

4.b=a++; = b=a;         c=++a; =  a=a+1;

          a=a+1;                  c=a;

5.for****循环是  计数器控制的循环的简写

6.include

  pow(x,y)  x的y次方

  1. setw 设置宽度 left right 默认向右对齐  向左:cout<<left<<……   

cout<<setw( )<<number,

8.do while 先执行一次再判断,while先判断

9.switch( ) 括号中的变量是整数或字符

10.cin.get()   从键盘中得到一个字符,用static_cast<>()将字符转化为ASC码

11.类 对象 属性和行为 cin是一个对象,get是它的行为 istream是类

12.int可用short ,long ,unsigned int,

13.break跳出这个循环块 continue结束本次循环

14.逻辑运算 && And ,| | or

15.bool 数据类型

16.Lvalues左值 Rvalues右值  变量是左值,因此可以出现在赋值号的左边。数值型的字面值是右值,因此不能被赋值,不能出现在赋值号的左边.

17recursion 递归 function  函数

返回值是因变量的值

18.argument****实参  parameter形参在函数原型和头中(声明函数或调用函数时)

  1. C++版本借助库,调用方式bitset(num),其中 len: 二进制输出的位数,提前自定义; num:要转成二进制的数。

20 .function prototype****函数原型 同一作用域中函数签名(函数名称和参数类型,数量)不能相同

21.argument coercion将实参变为形参的数据类型

22.数据类型 bool char int float double

23.promotion rules (不丢失信息):1)在混合类型的表达式中所有类型都变为其中最高的类型,最初的数据不变,创造临时的数据参与计算 2)argument coercion

24要从高到低转化用static_cast(total)

25. 定义常量 const int max=10;

26. i=rand()

27.1-6的随机数 :  1+rand()%6

28.enum Month{    }  枚举 直观

   Month month

29. 计算单次结果的累加或累乘器要清零或变为一,对多次结果运算的则不用****

30.使用除法时,如果两个数都是整数,结果是小学除法的结果,如1/d在d是int类型时若d>1结果总是0

31. 存储类别(决定变量存储的时间),作用域scope(在什么范围可以使用)

auto  局部变量和参数是automatic storage class(一般省略)

register 寄存器型变量 auto包括auto,register

static静态存储类,包括extern( 函数外声明;全局变量),static (函数内声明,定义后会一直在内存中,局部变量;调用结束后值会保留到下次调用;若不明确定义,值为0)

全局作用域(文件作用域)函数作用域 块作用域 函数原型作用域 (int f(int);可以不要那个x)

32.数据结构

Stack先进后出

33.int &count=a(按引用传递)count是a 的别名(引用)不会再建一个副本

34.默认实参 定义在函数名称第一次出现的地方

  1. : : 使用全局变量

36.重载函数:名字相同,参数不同

37.函数签名包括函数名和参数

38模板 template

  1. 递归:自己调用自己   大量的入栈出栈会耗费内存

40.递归是选择结构,迭代是循环结构

41.类中包括数据成员(成员变量)和成员函数  默认是private能管很多行直到下一个限定词

  1. .h文件放一个类的声明(接口);.cpp文件放具体的实现;函数原型和函数实现

43.构造函数名字和类的名字一样,没有返回类型 用于对象的初始化 使用时

类名 对象名(参数,参数)会有一个默认的构造函数(没有参数)如果你不构造

44.set函数:访问私有变量;检查私有变量的设置(可以在函数中设置报错,比如if语句)

45结构体struct,就是没有成员函数的类,结构体中默认是public

46.int c[ 3]={1},剩下两个会变成0

47.字符数组定义时可以不写数组的大小

48.cin读到空格就停了

49.每个字符数组不一定表示一个字符串,直接输出就是输出到‘/n’

50.将数组传给函数时是引用传递,数组名称和大小分开写

51.元素是单个字符,最后要加‘\0’

52 类变量 在数据成员前加static,所有对象共用一个copy,没有对象时也可通过类名加::加static的数据成员来使用

53.搜索    linear search线性搜索 平均要比较一半元素 如果找不到通常返回-1

54.排序    insertion sort 插入式排序(一般两个循环)

55.定义二维数组时行数可省,列数不可省

 

 

1.1 Fill in the blanks in each of the following statements: a) The company that popularized personal computing was Apple. b) The computer that made personal computing legitimate in business and industry was the IBM Personal Computer. c) Computers process data under the control of sets of instructions called program. d) The key logical units of the computer are the input unit, output unit, memory unit, arithmetic and logic unit, central processing unit and secondary storage unit. e) The three types of languages discussed in the chapter are machine languages, assembly languages and high-level languages. f) The programs that translate high-level language programs into machine language are called compliers. g)Android is a smartphone operating system based on the Linux kernel and Java. h)Release candidate software is generally feature complete and (supposedly) bug free and ready for use by the community. i) The Wii Remote, as well as many smartphones, uses a(n) accelerometer which allows the device to respond to motion.

1.2 Fill in the blanks in each of the following sentences about the C++ environment. a) C++ programs are normally typed into a computer using a(n) editor program. b) In a C++ system, a(n) preprocessor program executes before the compiler’s translation phase begins. c) The linker program combines the output of the compiler with various library functions to produce an executable program. d) The loader program transfers the executable program from disk to memory.

1.3 Fill in the blanks in each of the following statements (based on Section 1.6): a) Objects have the property of information hiding —although objects may know how to communicate with one another across well-defined interfaces, they normally are not allowed to know how other objects are implemented. b) C++ programmers concentrate on creating classes, which contain data members and the member functions that manipulate those data members and provide services to clients. c) The process of analyzing and designing a system from an object-oriented point of view is called object-oriented analysis and design(OOAD). d) With inheritance, new classes of objects are derived by absorbing characteristics of  existing classes, then adding unique characteristics of their own. e)The Unified Modeling Language(UML) is a graphical language that allows people who design software systems to use an industry-standard notation to represent them. f) The size, shape, color and weight of an object are considered attributes of the object’s class.

Fill in the blanks in each of the following statements:

a) The logical unit of the computer that receives information from outside the computer

for use by the computer is the input unit.

b) The process of instructing the computer to solve a problem is called programming.

c)Assembly languages is a type of computer language that uses English-like abbreviations for machine-language instructions.

d)Output unit is a logical unit of the computer that sends information which has already

been processed by the computer to various devices so that it may be used outside the

computer.

e)Memory or primary memory and secondary storage unit are logical units of the computer that retain information.

f)Arithmetic and logical unit is a logical unit of the computer that performs calculations.

g)Arithmetic and logical unit is a logical unit of the computer that makes logical decisions.

h)High-level ianguages languages are most convenient to the programmer for writing programs quickly and easily.

i) The only language a computer can directly understand is that computer’s machine language.

j)Central processing unit is a logical unit of the computer that coordinates the activities of all the other logical units.

1.5 Fill in the blanks in each of the following statements:

a)Java is used to develop large-scale enterprise applications, to enhance the functionality of web servers, to provide applications for consumer devices and for many other purposes.

b)C initially became widely known as the development language of the Unix operating system.

c) The Web 2.0 company Groupon is the fastest growing company ever.

d) The C++ programming language was developed by Bjarne Stroustrup in the early

1980s at Bell Laboratories.

1.6 Fill in the blanks in each of the following statements:

a) C++ programs normally go through six phases—edit ,preprocess ,compile ,link, load and execute .

b) A(n) integrated development environments(IDEs) provides many tools that support the software development process, such as editors for writing and editing programs, debuggers(调试) for locating logic errors in programs, and many other features.

c) The command java invokes the JVM, which executes Java programs.

d) A(n) virtual machine is a software application that simulates a computer, but hides the underlying operating system and hardware from the programs that interact with it.

e) The class loader takes the .class files containing the program’s bytecodes and transfers

them to primary memory.

f) The  bytecode verifier examines bytecodes to ensure that they’re valid

 

 

Fill in the blanks in each of the following.

a) Every C++ program begins execution at the function main.

b) A(n)left brace begins the body of every function and a(n) right brace ends the body.

c) Every C++ statement ends with a(n) semicolon .

d) The escape sequence \n represents the  newline character, which causes the cursor to

position to the beginning of the next line on the screen.

e) The if statement is used to make decisions.

State whether each of the following is true or false. If false, explain why. Assume the statement using std::cout; is used.

a) Comments cause the computer to print the text after the // on the screen when the program is executed. Comments do not cause any action to be performed when the program is executed. They’re used to document programs and improve their readability

b) The escape sequence \n, when output with cout and the stream insertion operator,

causes the cursor to position to the beginning of the next line on the screen.

c) All variables must be declared before they’re used.

d) All variables must be given a type when they’re declared.

e) C++ considers the variables number and NuMbEr to be identical. C++ is case sensitive, so these variables are unique

f) Declarations can appear almost anywhere in the body of a C++ function.

g) The modulus operator (%) can be used only with integer operands.

h) The arithmetic operators *, /, %, + and – all have the same level of precedence. The operators *,/ and % have the same precedence, and the operators + and – have a lower precedence

i) A C++ program that prints three lines of output must contain three statements using

cout and the stream insertion operator. One statement with cout and multiple \n escape sequences can print several lines

Fill in the blanks in each of the following:

a) Comments are used to document a program and improve its readability.

b) The object used to print information on the screen is cout.

c) A C++ statement that makes a decision is if.

d) Most calculations are normally performed by assignment statements.

e) The cin object inputs values from the keyboard.

State which of the following are true and which are false. If false, explain your answers.

a) C++ operators are evaluated from left to right. They are evaluated according to their precedence and associativity

b) The following are all valid variable names: under_bar, m928134, t5, j7, her_sales,

his_account_total, a, b, c, z, z2.

c) The statement cout << "a = 5;"; is a typical example of an assignment statement. This statement will just print a=5; to the screen. It does not perform any assignment in the program

d) A valid C++ arithmetic expression with no parentheses(括号) is evaluated from left to right. It will be evaluated according to their precedence and associativity

e) The following are all invalid variable names: 3g, 87, 67h2, h22, 2h. h22 is a valid variable name . All of the other variable names start with digits and are therefore invalid variable names

Fill in the blanks in each of the following:

a) What arithmetic operations are on the same level of precedence as multiplication?

/ ,%.

b) When parentheses are nested, which set of parentheses is evaluated first in an arithmetic expression? . the innermost set of parentheses

c) A location in the computer’s memory that may contain different values at various times

throughout the execution of a program is called a(n) variable.

 

Fill in the blanks in each of the following:

a) Every class definition contains the keyword class followed immediately by the

class’s name.

b) A class definition is typically stored in a file with the .h filename extension.

c) Each parameter in a function header specifies both a(n) type and a(n) name.

d) When each object of a class maintains its own copy of an attribute, the variable that represents the attribute is also known as a(n) data member.

e) Keyword public is a(n)access specifier .

f) Return type void indicates that a function will perform a task but will not return

any information when it completes its task.

g) Function getline from the library reads characters until a newline character

is encountered, then copies those characters into the specified string.

h) When a member function is defined outside the class definition, the function header

must include the class name and the binary scope resolution operator(::) , followed by the function name to “tie” the member function to the class definition.

i) The source-code file and any other files that use a class can include the class’s header via #include a(n) preprocessor directive(预处理指令).

3.2 State whether each of the following is true or false. If false, explain why.

a) By convention(按照惯例), function names begin with a capital letter(大写字母) and all subsequent(随后的) words in the name begin with a capital letter. Function names begin with a lowercase letter and all subsequent words in the name begin with a capital letter

b) Empty parentheses following a function name in a function prototype indicate that the function does not require any parameters to perform its task.

c) Data members or member functions declared with access specifier private are accessible to member functions of the class in which they’re declared.

d) Variables declared in the body of a particular member function are known as data members and can be used in all member functions of the class. Such variables are local variables and can be used only in the member function in which they are declared

e) Every function’s body is delimited by left and right braces ({ and }).

f) Any source-code file that contains int main() can be used to execute a program.

g) The types of arguments in a function call must be consistent with the types of the corresponding parameters in the function prototype’s parameter list.

 

 

 

4.1 Answer each of the following questions.

a) All programs can be written in terms of three types of control structures: sequence, selection and  repetition.

b) The if…else selection statement is used to execute one action when a condition is true or a different action when that condition is false.

c) Repeating a set of instructions a specific number of times is called counter-controlled or definite repetition.

d) When it isn’t known in advance how many times a set of statements will be repeated, a(n) sentinel, signal, flag or dummy value can be used to terminate the repetition.

 

 

5.1 State whether the following are true or false. If the answer is false, explain why.

a) The default case is required in the switch selection statement. The default case is optional . Nevertheless, it is considered good software engineering to always provide a default case

b) The break statement is required in the default case of a switch selection statement to exit the switch properly. The break statement is used to exit the switch statement. The break is not required when the default case is the last case . Nor will the break statement is required if having control proceed with the next case makes sense (如果继续处理下一条语句是有意义的)

c) The expression ( x > y && a < b ) is true if either the expression x > y is true or the expression a<b is true. When using the && operator, both of the relational expressions must be true for the entire expression to be true

d) An expression containing the || operator is true if either or both of its operands are true

 

 

6.1 Answer each of the following:

a) Program components in C++ are called functions and classes.

b) A function is invoked(调用) with a(n) function call .

c) A variable known only within the function in which it’s defined is called a(n) local variable.

d) The return statement in a called function passes the value of an expression back to the calling function.

e) The void keyword is used in a function header to indicate that a function does not return a value or to indicate that a function contains no parameters.

f) An identifier’s scope is the portion of the program in which the identifier can be used.

g) The three ways to return control from a called function to a caller are return, return expression and encounter the closing right brace of a function.

h) A(n) function prototype allows the compiler to check the number, types and order of the arguments passed to a function.

i) Function rand is used to produce random numbers.

j) Function srand is used to set the random number seed to randomize the number sequence generated by function rand.

k) The storage-class specifiers are mutable, auto , register , extern and static.

l) Variables declared in a block or in the parameter list of a function are assumed to be of auto storage class unless specified otherwise.

m) Storage-class specifier register is a recommendation to the compiler to store a variable in one of the computer’s registers.

n) A variable declared outside any block or function is a(n) global variable.

o) For a local variable in a function to retain its value between calls to the function, it must be declared with the storage-class specifier static.

p) The six possible scopes of an identifier are function scope , global namespace scope , local scope , function-prototype scope , class scope and namespace scope .

q) A function that calls itself either directly or indirectly (i.e., through another function)

is a(n) recursive function.

r) A recursive function typically has two components—one that provides a means for the recursion to terminate by testing for a(n) base case and one that expresses the problem as a recursive call for a slightly simpler problem than the original call.

s) It’s possible to have various functions with the same name that operate on different types or numbers of arguments. This is called overloading function .

t) The unary scope resolution operator(::) enables access to a global variable with the same name as a variable in the current scope.

u) The const qualifier is used to declare read-only variables.

v) A function template enables a single function to be defined to perform a task on many

different data types.

 

 

7.1 (Fill in the Blanks) Answer each of the following:

a) Lists and tables of values can be stored in array or vector .

b) The elements of an array are related by the fact that they have the same array name and type.

c) The number used to refer to a particular element of an array is called its subscript or index.

d) A(n) constant variable should be used to declare the size of an array, because it makes the program more scalable.

e) The process of placing the elements of an array in order is called the array sorting.

f) The process of determining if an array contains a particular key value is called the array searching.

g) An array that uses two subscripts is referred to as a(n) two-dimensional array.

7.2 (True or False) State whether the following are true or false. If the answer is false, explain why.

a) An array can store many different types of values. An array can store only values of the same type

b) An array subscript should normally be of data type float. An array subscript should be an integer or an integer expression

c) If there are fewer initializers in an initializer list than the number of elements in the array, the remaining elements are initialized to the last value in the initializer list. The remaining elements are initialized  to zero

d) It’s an error if an initializer list has more initializers than there are elements in the array.

e) An individual array element that is passed to a function and modified in that function

will contain the modified value when the called function completes execution. Individual elements of an array are passed by value. If the entire array is passed to a function , then any modifications to the elements will be reflected in the original.

Fill in the blanks in each of the following:

a) The names of the four elements of array p (int p[4];) are p[0] , p[1] , p[2] and p[3] .

b) Naming an array, stating its type and specifying the number of elements in the array is called the array declaring.

c) By convention, the first subscript in a two-dimensional array identifies an element’s row and the second subscript identifies an element’s column .

d) An m-by-n array contains m rows, n columns and m*n elements.

e) The name of the element in row 3 and column 5 of array d is d[2][4].

7.7 (True or False) Determine whether each of the following is true or false. If false, explain why.

a) To refer to a particular location or element within an array, we specify the name of the

array and the value of the particular element. Refer to the position number, not element

b) An array definition reserves space for an array.

c) To indicate reserve 100 locations for integer array p, you write the declaration

p[ 100 ]; the declaration is int p[100];

d) A for statement must be used to initialize the elements of a 15-element array to zero. The statement p[15]={0}; can be used

e) Nested for statements must be used to total the elements of a two-dimensional array. Nested while statement or nested do…while statement can be used

8.1 Answer each of the following:

a) A pointer is a variable that contains as its value the address of another variable.

b) The three values that can be used to initialize a pointer are 0, NULL and

an address.

c) The only integer that can be assigned directly to a pointer is 0.

8.2 State whether the following are true or false. If the answer is false, explain why.

a) The address operator & can be applied only to constants and to expressions. The operand of the address operator must be a lvalue, the address operator cannot be applied to constants or to expressions that do not result in references

b) A pointer that is declared to be of type void * can be dereferenced. A pointer to void cannot be dereferenced.  such a pointer does not have a type that enables the compiler to determine the number of bytes of memory to dereference and the type of the data to which the pointer points

c) A pointer of one type can’t be assigned to one of another type without a cast operation.

pointers of any type can be assigned to void pointers. Pointers of type void can be assigned to pointers of other types only with an explicit type cast.

8.7 (True or False) State whether the following are true or false. If false, explain why.

a) Two pointers that point to different arrays cannot be compared meaningfully.

b) Because the name of an array is a pointer to the first element of the array, array names

can be manipulated in precisely the same manner as pointers. The name of an array is a constant pointer whose value can not be changed