C++ Object-Oriented Programming (2nd Edition) Chapter 1 (Preliminary Knowledge of C++) Summary of Knowledge Points

C++ object-oriented programming

参考书目:《C++面向对象程序设计》—— 谭浩强 《C++程序设计:思想与方法》—— 翁惠玉



1. From C to C++

       C language is a structured and modular language. The designer of a C program must carefully design every detail of the program and accurately consider what happens at every moment when the program is running. When the program size becomes larger, structured programs The design seems inadequate.
       In order to solve the software design crisis, the object-oriented programming idea (OOP) was proposed in the 1980s. In practice, people found that the C language is so widely used that if an object-oriented language is developed based on it, it will definitely make It was easy for the public to accept this language, so C++ was born.
       C++ can be used for both process-oriented structured programming and object-oriented programming.

2. Lexical and lexical rules of C++ language

1.Character set of C++ language

       Character set equivalent to C language, including:

  • Uppercase and lowercase English letters
  • Numeric characters
  • Other ASCII characters (except @, $)

2. Words and lexical rules

       Words are one of the key components that make up a statement. They usually consist of several characters. C++ has several types of words:

  • Keywords
           are command words in the C++ language. They are predefined words, and the C++ compiler has a special interpretation of them. Such as: int, float, if, else, while, switch, etc.
  • Identifiers
           Programmers use identifiers to name elements in the program, including function names, class names, object names, type names, variable names, constant variable names, array names, etc. Identifiers start with letters or underscores, followed by letters, numbers, and underscores (identifiers are case-sensitive) .
  • Operator
           An operator is a word that represents a certain operation and consists of one or more characters (note the priority and combination order of operators) .
  • Delimiters
           should be used to separate keywords and identifiers in statements and between statements. Commonly used delimiters in C++ include spaces, commas, semicolons, colons, and braces.
  • Comment
           C++ provides two comment characters. /* Comments* / (Multi-line comments) // Comments (Single-line comments)

3. The simplest C++ program

1. Output characters

Example 1: Output a line of characters "This is a C++ program."

#include <iostream>          //用cout输出时需要用此头文件
using namespace std;        //使用命名空间std
int main()
{
    
    
    cout<<"This is a C++ program.\n";      //用C++的方法输出一行
    return 0;
}

注: (1)C++程序中常用cout、cin进行输出输入,cout是C++定义的输出流对象,<<是插入运算符。 (2)使用cout、cin需要用头文件iostream,在程序开始要用#include声明包含的头文件。 (3) using namespace std; 意思是使用命名空间。C++标准库中的类和函数是在命名空间std中声明的,因此程序中如用C++标准库中的有关内容,就要用using namespace std; 语句声明。 (4)标准C++规定main函数必须声明为int类型,如果程序正常运行,向操作系统返回一个零值,否则返回非零值,通常是-1。

2. Numerical operations

Example 2: Find the sum of two numbers a and b

#include <iostream>        //预处理命令
using namespace std;      //使用命名空间std
int main()                    //主函数首部
{
    
                                 //函数体开始
    int a,b,sum;              //定义变量
    cin>>a>>b;                //输入语句
    sum=a+b;                  //赋值语句
    cout<<"a+b="<<sum<<endl;      //输出语句
    return 0;                    //如程序正常结束,返回一个零值
}

Insert image description here
注: (1)在程序执行时,键盘输入的第一个数据赋予a,第二个数据赋予b 。 (2)cout语句中的endl是C++控制符常数,作用是让光标换行。

3. Numerical comparison

Example 3: Find the larger of two numbers

#include <iostream>
using namespace std;
int main()
{
    
     
    int max(int x,int y) ;         //对max函数作声明
    int a,b,c;
    cin>>a>>b;
    c=max(a,b);                   //调用max函数
    cout<<"max="<<c<<endl;
    return 0;
}
int max(int x,int y)            //定义max函数
{
    
     
    int z;
    if(x>y) z=x;
    else z=y;
    return(z);
}

Insert image description here
注: (1)本程序包含两个函数,主函数main和被调用的函数max。 (2)max函数的作用是将两个整数中的大数赋予变量z。return语句将z的值返回给主函数main。返回值是通过函数名max带回到main函数的调用处。

4.C++ class

Example 4: C++ program containing classes

#include <iostream>                 
using namespace std;
class Student             //声明一个类,类名为Student
{
    
      
   private:                   //以下为类中的私有部分
      int num;                //私有变量num
      int score;             //私有变量score
   public:                   //以下为类中公用部分
   void setdata()           //定义公用函数setdata
    {
    
    cin>>num;              //输入num的值
     cin>>score;}          //输入score的值
   void display()          //定义公用函数display
    {
    
    cout<<"num="<<num<<endl;          //输出num的值
     cout<<"score="<<score<<endl;};   //输出score的值
};                                    //类的声明结束
Student stud1,stud2;      //定义stud1和stud2为Student类的变量,称为对象
int main()               //主函数首部
{
    
    
    stud1.setdata();   //调用对象stud1的setdata函数
    stud2.setdata();   //调用对象stud2的setdata函数
    stud1.display();   //调用对象stud1的display函数
    stud2.display();   //调用对象stud1的display函数
    return 0;
}

Insert image description here
注: (1)程序中声明一个被称为类的类型Student。声明时要用关键字class。C++类中可以包含数据(如变量num、 score)和函数(如setdata函数和 display函数),分别称为数据成员和成员函数。 (2)在C++ 中将一组数据和访问这组数据的函数封装在一起,组成类。一个类是由一组数据,一组对其访问的若干函数,以及数据和函数的访问属性组成的。在前面程序中看到的private(私有)public(公有)保留字代表数据和函数的访问属性。 (3)凡是指定为公有的数据和函数,既可由本类的函数访问和调用,也可由其他函数或语句访问和调用;凡是指定为私有的数据和函数,通常只能由本类的函数访问和调用。 (4)程序中“Student stud1,stud2; ”是一个定义语句,定义两个Student 类型变量stud1和stud2,Student 类与int一样是C++的合法类型。 (5)具有“类”类型的变量称为对象。 Student的对象stud1,stud2具有同样的结构和特征。 (6)在类外调用成员函数时必须在函数名前冠以类的名称。

4. C++ extension to C

       In order to be compatible with C, C++ retains some regulations in the C language, such as the file name of the header file. The extension of the header file in the C language is .h. Many C++ compilation systems retain this extension. The C++ compiler launched in recent years The new version of the system has introduced a number of header files without extensions such as iostream, string, cmath, etc. For compatibility with C++, header files with extensions are still allowed. Since the C language has no namespace, you do not need to use namespace std when using header files with extensions.
       C++ inherits most of the functions and grammatical provisions provided by the C language, and expands on this basis.

1.Input and output of C++

       For the convenience of use, C++ not only uses the printf and scanf functions for input and output, but also adds the standard input stream and output stream cin and cout. They are defined in the header file iostream. The standard stream is a streaming file that can be directly operated without opening and closing the file. The standard input stream here refers to the data input from the keyboard, and the standard output stream refers to the screen output. data flow.
Insert image description here

  • Use cout for output
    format: cout <<Expression 1[<<Expression 2...]
    Function: Calculate the value of the expression one by one from left to right, and insert it into the output stream cout.
    Usage: cout must be used together with the output operator <<. Each << is followed by an expression. The combination direction of the << operator is from left to right, so the values ​​of each expression are inserted into the sequence from left to right. in the output stream.
  • Use cin for input
    format: cin>>Variable 1 [>>Variable 2...]
    Function: >> is the extraction operator of C++, which means to obtain data from the standard input device and assign it to the subsequent variables.
    Usage: When entering numerical data from the keyboard, separate the two data with a space or a carriage return.
    Insert image description here

2. Use const to define constant variables

       Format: const type variable name = constant
       Example: const float PI= 3.14159;

3. Function prototype declaration

       Format: function type function name (formal parameter list);
       example: int max (int x, int y);

4. Overloading of functions

       C++ allows multiple functions to be defined with one function name in the same domain. These functions have different number of parameters and different parameter types. Using one function name to implement different functions is called function overloading.

Example: Calculate the maximum number among three numbers (type overloading)

#include <iostream>
using namespace std;
int max(int a,int b,int c)           //求3个整数中的最大者
{
    
     if (b>a) a=b;
if (c>a) a=c;
return a; 
} 
float max(float a,float b, float c)  //求3个实数中的最大者
{
    
    if (b>a) a=b;
 if (c>a) a=c;
 return a; 
} 
long max(long a,long b,long c)  //求3个长整数中的最大者
{
    
    if (b>a) a=b;
 if (c>a) a=c;
 return a;
}
int main( )
{
    
    int a,b,c;  float d,e,f;  long g,h,i;
cin>>a>>b>>c; 
cin>>d>>e>>f;
cin>>g>>h>>i;
int m;
m= max(a,b,c);                        //函数值为整型
cout <<"max_i="<<m<<endl;
float n;
n=max(d,e,f);                          //函数值为实型
cout<<"max_f="<<n<<endl;
long int p;
p=max(g,h,i);                          //函数值为长整型
cout<<"max_l="<<p<<endl;
return 0;
}

Insert image description here

Example: Calculate the maximum number among three numbers (function overloading)

#include <iostream>
using namespace std;
int max(int a,int b,int c)     //求3个整数中的最大者
{
    
    if (b>a) a=b;
 if (c>a) a=c;
 return a;
}
int max(int a, int b)         //求两个整数中的最大者
{
    
    if (a>b) return a;
 else return b;
}
int main( )
{
    
    int a=7,b=-4,c=9;
 cout<<max(a,b,c)<<endl; //输出3个整数中的最大者
 cout<<max(a,b)<<endl;  //输出两个整数中的最大者
 return 0;
}

Insert image description here
注:不允许函数参数个数、参数类型都相同,只是函数返回值不同。因为系统无法从调用形式上判断调用与哪个函数相匹配。

5. Function template

       If the number of parameters of two functions is the same, the behavior of the function is the same (does the same thing), but the data types of the function and parameters are different. If you use function overloading, the function code written is the same. In order to save time, C++ Provides function template functionality.
       Format: template typename identifier [, typename identifier, ... ]
       Function: The so-called function template is to create a general function without specifying the function type and parameter type, but using a virtual type to represent it. When calling a function, the virtual types in the template are replaced by the types of the actual parameters.

Example: Define a function template for calculating the larger of two numbers

#include <iostream>
using namespace std;
template <typename T>
T max(T a,T b,T c)  //用虚拟类型T表示类型
{
    
    if(b>a) a=b;
 if(c>a) a=c;
 return a;
}
int main()
{
    
    int i1=8,i2=5,i3=6,i;
 double d1=56.9,d2=90.765,d3=43.1,d;
 long g1=67843,g2=-456,g3=78123,g;
 i=max(i1,i2,i3);
 d=max(d1,d2,d3);
 g=max(g1,g2,g3);
 cout<<"i_max="<<i<<endl;
 cout<<"d_max="<<d<<endl;
cout<<"g_max="<<g<<endl;
 return 0;
}

Insert image description here
注:函数模板只适用于函数参数的个数相同而类型不同,并且函数体相同的情况,如果函数的参数个数不同,则不能用函数模板。

6. Functions with default parameters

       C++ allows setting default values ​​for function parameters. When the function is called, if there are no actual parameters, the default value will be used as the actual parameter value.
       Format: Formal parameter type Formal parameter variable name = constant
       Function: When calling a function, if there is no actual parameter, the constant will be used as the value of the formal parameter; if there is an actual parameter, the value of the actual parameter will still be used as the value of the formal parameter.

Example: Write a function to calculate the volume of a cylinder
float volume (float h, float r = 12.5)

调用可以采用以下任何一种形式:
	volume( 45.6);
	volume( 32.5, 10.5);
	用第一种方式调用时,只有一个实参,圆半径的值取默认值12.5.
	用第二种方式调用时,有两个实参,圆半径的值取实参的值10.5

注: (1)有默认值的形参必须放在形参表的右边,不允许无默认参数值和有默认参数值的形参交错排列。 (2)一个函数名不能同时用于重载函数和带默认形参值的函数。当调用函数时,如少写一个参数,系统无法判断是利用重载函数还是利用带默认参数值的函数,出现二义性。

7. Reference to variables

       C++ provides the function of aliasing variables, which is the reference of variables.
       Format: Type & Variable 1 = Variable 2
       Variable 2 is a variable that has been defined before and has the same type as variable 1. Here, an alias variable 1 is defined for variable 2. In the program, variable 1 and variable 2 are the same variable.

#include <iostream>
using namespace std;
int main( )
{
    
    int a=10;
 int &b=a;    //声明b是a的引用
 a=a*a;       //a的值变化了,b的值也应一起变化
 cout<<a<<"  "<<b<<endl;   
 b=b/5;        //b的值变化了,a的值也应一起变化
 cout<<b<<"  "<<a<<endl;
 return 0;
}

Insert image description here
Insert image description here
注:两个变量不能用同一个别名。
       In addition to using ordinary variables and pointer variables as formal parameters, C++ can also use reference variables as formal parameters.
       (1) When ordinary variables are used as formal parameters
       , the value of the actual parameter is passed. In the function, the formal and actual parameters are two different memory units. Modification of the formal parameters will not affect the value of the actual parameter.

#include <iostream>
using namespace std;
void swap(int a,int b)
{
    
     int temp;
 temp=a;
 a=b;
 b=temp;                //  实现a和b的值互换
}
int main( )
{
    
    int i=3,j=5;
 swap(i,j);
 cout<<i<<","<<j<<endl;   //  i和j的值未互换
 return 0;
}

Insert image description here
       (2) Using pointer variables as formal parameters
       C language also allows using pointer variables as formal parameters. At this time, the address (pointer) of the actual parameter variable is passed, and this pointer is used to access the actual parameter variable within the function.

#include <iostream>
using namespace std;
void swap(int *p1,int *p2)
{
    
    int temp;
 temp=*p1;
 *p1= *p2;
 *p2=temp;
}
int main( )
{
    
    int i=3,j=5;
 swap(&i,&j);
 cout<<i<<","<<j<<endl;
 return 0;
}

Insert image description here
       (3) Use reference variables as formal parameters
       and use pointer variables as formal parameters. It passes the address of the actual parameter variable to the formal parameter, and uses the "* pointer variable" method to access the actual parameter variable within the function. We know that reference variables are aliases of variables. When calling a function, the formal parameter made by the reference variable becomes the alias of the actual parameter variable. The formal parameter name used in the function is the alias of the actual parameter. This is more convenient than using pointer variables. Intuitive and more convenient.

#include <iostream>
using namespace std;
void swap(int &a,int &b)
{
    
    int temp;
 temp=a;
 a=b;
 b=temp;
}
int main( )
{
    
    int i=3,j=5;
 swap(i,j);
 cout<<"i="<<i<<"   "<<"j="<<j<<endl;
 return 0;
}

Insert image description here
注: (1)引用变量都具有非void类型 (2)不能建立引用的数组 (3)可以建立常引用变量,不允许修改常引用变量的值

8. Built-in functions

       C++ provides a mechanism to embed the code of the called function into the calling function code during compilation, eliminating the calling link when executing the function and improving the execution speed of the function. This mechanism is called a built-in function, and some books call it an inline function.
       Format: inline function type function name (formal parameter list)
                  {function body}
       Calling format: function name (actual parameter list)

Example: Calculate square roots using built-in functions

#include <iostream>
using namespace std;
inline int power(int x)       //定义内置函数
{
    
    return x*x;}
int main()
{
    
    cout<<power(2)<<endl;
 cout<<power(1+1)<<endl;
 return 0;
}

注:使用内置函数可以节省程序的运行时间,但增加了目标程序的长度。所以在使用时要衡量时间和空间的得失。

9. Scope operator

       Each variable has its own effective scope. The program can only use variables within the effective scope of the variable and cannot directly use variables in other domains.
Insert image description here

Example: local variables and global variables have the same name

#include <iostream>
	using namespace std;
	float a=13.5;
	int main( )
	{
    
        int a=5;
	     cout<<a<<endl;
	     return 0;    }

       There are two variables a in the program, one is a global variable and the other is a local variable of the main function. According to the rule that local variables will mask global variables with the same name, the variable a that appears in the function is a local variable, so the output value is 5 , instead of 13.5, in order to access global variables in a function, C++ provides the scope operator::, which can be used to specify the scope to be accessed. The main function can be rewritten as

#include <iostream>
	using namespace std;
	float a=13.5;
	int main( )
	{
    
    int a=5;
	cout<<a<<endl;
	cout<<::a<<endl;
	 return 0;
	}
	::a表示全局变量a。注意不能用::访问局部变量。

10. String variables

       C++ provides the string class type string. In fact, it is not a basic type of C++. It is a string class declared in the C++ standard library, and programs can use it to define objects.

  • Define string variable
    format: string variable name table;
    注:如用字符串变量,在程序开始要用包含语句把C++标准库的string头文件包含进来。
  • Perform string operations
    (1) Assign a value to a string variable
    String variable = String expression
    Insert image description here
    (2) Access characters in a string
    C++ allows strings to be used as character arrays. The subscript of the first character is 0, and the subscript of the second character is 0. The subscript of characters is 1, and so on.
string  w = "then";
 	    w[2] = "a";

       (3) Input and output string
       cin >> String variable
       cout << String variable
       (4) String connection operation
       format: String 1 + String 2

string  st1=“C++;
string  st2=“Language”;
st1 = st1 + st2 ;

       (5) String comparison operations
       can use the relational operators >, >=, ==, !=, <, <= to compare characters at the same position in two strings, and determine the size of the characters based on the ASCII code value.

”china” > “chinese”
运算结果是假。

11. Operators for dynamically allocating/destroying memory

       Format: new type [(initial value)]
       The type is the key element that determines the size of the allocated space. If the operation result is correct, its value is the starting address of the allocated memory space, otherwise NULL is returned.
       Format: delete[] The pointer variable
       deletes the dynamic memory space pointed by the pointer variable. The data type of the pointer variable determines the size of the space.

Example: Use dynamic memory to store structure variables

#include <iostream>
#include <string.h>
using namespace std;
struct student 
{
    
    char name [10];
 int num;
 char sex;
};
int main ( )
{
    
    student *p;
 p=new student;
 strcpy_s(p->name,"Wang Fun");
 p->num=10123;
 p->sex='M';
 cout<<p->name<<"  "<<p->num<<"  "<<p->sex<<endl;
 delete p;
 return 0;
}

Insert image description here

5. Writing and Implementation of C++ Programs

Insert image description here

Guess you like

Origin blog.csdn.net/weixin_43312470/article/details/108045857