Process-oriented C ++ programming

Foreword

C language is a process-oriented programming language, C ++ is an object-oriented programming language, which are two different programming languages. C language is a subset of C ++, C ++ is a superset of the C language, C ++ to further expand and improve the C language, most of which are to develop object-oriented programming. Process C ++ programming language C may either be designed, and can be characterized in an abstract data type based design program objects may also be carried out inheritance and polymorphism characterized by object-oriented program design.

From "Hello world!" Let's talk about

Inheriting fine traditional learning programming languages, we have to write a "Hello world!":

#include <iostream>
using namespace std;
int main()
{
   cout << "Hello World";
   return 0;
}

class

Category (class) of user-defined data type, a type of construction, with a structure similar to the C language, but some extensions to the members of the class may not only be variable, may also be a function of the variables defined by the class out there are also specific title, called "objects." Type generally divided into two parts, which are written in different documents, one of which is the header file is used to declare classes provide this function, the other file contains the complete code for these operations. Want to use the class, you must include the header file in the program now.

Standard "input / output library."

In the C ++ standard "input / output library" named "iostream", iostream word is composed of three parts, i.e. the iostream, stream input and output means. Contains many classes for input and output in iostream class library includes classes support input and output terminal and file. We have to contain Header files, can use the input and output streams operation.

cin and cout

cout (pronounced see out) and cin (pronounced see in) is not an operator, not a keyword, they are C ++ built-in objects (objects created good advance). cin and cout are subject to ostream and istream classes, by the developer of the standard library to create a good advance, can be directly used to use.
Implemented in C ++ output and input is (Stream) "flow" mode, COUT is the standard output stream object, i.e. the ostream, CIN is the standard input stream object, i.e. an istream, off stream object cin, cout and flow calculation the character definitions stored in the database input and output streams, so if using cin, cout and operators in the program flow, must be included in the present document header file stream.

">>" and "<<" operator

symbol Features
>> output operator inserter can also be called, may be directed into the data stream, a data stream input to the
<< Operator input can also be called extractor, the input content may be directed to the object that has the appropriate type for the data input from the stream

E.g:

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string name;
    cin >> name;
    cout << "Hello, " 
             << name 
             << "!" 
             << endl; 
    return 0;
}

Operating results as follows:

In this code, we first define the object "string" type for storing contents input stream and then use cin ">>" operator, the contents of the input is stored in the "name" object, we we hope that the contents of the output in order by "<<" output to the cout stream. We can see that we do not need to enter some content on every write a "cout <<", can be connected to a series of output statements output statements to endl as the end.

endl

endl is the C ++ standard library manipulator, English meaning is end of line, that is the end of a line of output, often with the use of cout, which means the end of the output. Features are:

  1. The newline character to the output stream, and the brush device with the content of the buffer associated with the device, to ensure that the program temporarily stored so far are really all output to the output stream;
  2. Empty the output buffer.

What is "using namespace std" yes?

std is the name of the namespace in the standard library, any content provided by the standard library are encapsulated in the namespace std. A library namespace is encapsulated in the name of the method, the problem of naming conflicts can be avoided and applications occur.
Therefore, to use the string class and cin, cout objects in the program, in addition to include the header files, but also with the two keywords using namespace std namespace content exposure.

initialization

C ++ provides us with another way to initialize, or " constructor syntax ", like this:

int num(0);

But we mentioned initialization, it is natural that we will do:

int num = 1;

Of course, we do not have a problem, when we learn the C language are so dry. But why C ++ will provide another way to initialize it?
For example, C ++ Standard Library there is a class called complex class, a plurality of class object consists of two parts, namely the real and imaginary part, which also shows the initialization complex class object we need simultaneously to the real and imaginary initialization section, this time the original "with assignment operator (=) initializes not easy to use.
in order to solve the" multi-value initialization problem ", C ++ constructor is provided syntax:

#include <complex>
complex<double> purei(0,1);

Quote

What is a reference

The following wording defines a reference and initialize it to a variable reference.

类型名 & 引用名 = 变量名

Reference variable is an alias , equivalent to a variable reference this variable. The reference is initialized to a variable, you can use the reference name of the variable to point to the original variable names are still valid, you can still use the original variable names to point to variables. There are references to the following considerations:

  1. Can not be a null reference, you must initialize a variable to reference the definition of reference;
  2. References are single-mindedness, has been cited variables are initialized after initialization drinking, you can not reference other variables;
  3. Reference can only reference variables, constants, and expressions can not be referenced.

In order to understand more intuitive reference, we have to write the code section:

#include <iostream>
#include <string>
using namespace std;
int main()
{
    int num1(0);
    int & num2 = num1;
    
    cout << num2 << endl; 
    
    num1 = 1;
    cout << num1 << endl; 
    cout << num2 << endl;
    
    num2 = 2;
    cout << num1 << endl; 
    cout << num2 << endl;
    return 0;
}

Operating results as follows:

we first define an object of type int num1, then defines a reference num2. After we define a reference, num1 and num2 two of the same thing, our num1 num2 operation equivalent to the operation, so we modified after each output
num1 and num2 output data is the same.

Often quoted

When defining a reference, in the definition statement before adding the const keyword, this time to define a constant reference. Action is not often cited by reference in its reference to the content, it is written:

const 类型名 & 引用名 = 变量名
  • Often cited references can not modify the content, but the content itself may modify the referenced.

And very often cited references

And references cited are often very different types, and reference can be used to initialize the constant variable references, but often can not be used to initialize the references cited.

Examples


Let's look at reducing the error when we started to learn programming will commit:

void swap(int a,int b)
{
    int temp;
    temp = a;
    a = b;
    b = temp;
}

We all know that, so writing is wrong, as they relate to arguments and parameters problem. Incoming variable a, b is a copy of the original data, local variables, once the function completes, a, b two variables will disappear. That was how we address this issue? We can pass a pointer into the function, so that you can operate indirectly through a pointer variable.
But now we can use references to solve this problem:

#include <iostream>
#include <string>
using namespace std;

void swap(int & a,int & b);

int main()
{
    int num1(0);
    int num2(1);
    
    swap(num1, num2);
    cout << "num1 = " << num1 << endl; 
    cout << "num2 = " << num2 << endl;
    
    return 0;
}

void swap(int & a,int & b)
{
    int temp;
    temp = a;
    a = b;
    b = temp;
}

The output is:

We will a, b to the type of reference, as we, a will be referenced to the first argument passed by value function of time, b will refer to the second argument passed. According to the definition cited, a, b, respectively, and passed on two variables is one thing, and this time we operate a, b, equivalent to the operating parameters passed itself, you do not want that incoming address before a.

References and pointers

References and pointers have some similarities, they differ mainly three:

  1. Reference can not be null reference, reference must be connected to a legitimate memory. Pointer can be a null pointer.
  2. Reference is initialized to an object, then it can not be referenced by other objects. Another object pointers can point at any time.
  3. Reference must be initialized when created. Pointer may be initialized at any time.

Dynamic memory allocation

distribution

我们在C++中使用 new 运算符实现动态内存分配。
当我们只分配一个变量时,语法如下:

ptr = new Type

当我们分配一个数组时,语法如下:

ptr = new Type[N]
参数 说明
Type 任意类型名,可以是 class 类型
ptr Type* 类型的指针名
N 分配的数组元素个数,可以是整型表达式

使用 new 运算符之后,C++ 将分配出大小为 sizeof(Type) × N(分配变量时N为1) 的空间,并且将内存空间的起始地址赋值给 ptr 。

释放

有申请空间就一定要释放,否则会造成内存泄漏。用 new 运算符分配的内存空间需要用 delete 运算符释放。
申请变量时,释放语法为:

delete ptr;

申请指针时,释放语法为:

delete []ptr;
参数 说明
ptr 需要释放的空间的指针名,必须是动态内存分配出的空间
  • 我们无需检验 ptr 是否为空指针

new 和 malloc的区别

  1. new分配的空间不需要强制类型转换;
  2. new分配的空间不需要判空;
  3. new分配的空间时可以初始化。

缺省值

给函数参数赋默认值

在C++中,定义函数时,我们可以让最右边的连续若干个参数具有默认值,这个默认值叫做缺省值。调用参数的时候,若相应位置不写参数,那么该参数的值就会被赋值为缺省值。

实例


代码实现:

int add(int a, int b = 20, int c = 30)
{
    return a + b + c;
}

提供默认值的规则

  1. 默认值的解析操作从最右边开始。如果我们为某个参数提供了默认值,则该参数右侧的所有参数都必须具有默认值;
  2. 默认值只能指定一次,即函数声明和函数定义只能有一个地方指定默认值,不能两个地方都指定。
  • 为了提高可见性,建议默认值在函数声明的时候指定。

内联函数

为什么会有“内联函数”

当我们用函数封装代码时,函数的调用是有开销的,除了时间上的开销,频繁调用的函数也可能大量消耗栈空间。如果我们写了个功能强大的函数,这个函数有几百行,那么函数调用的开销相对会显得比较小,可以忽略不计,就好比分析卫星运行的轨道半径时不需要考虑卫星的长度参数一样。但是如果是个只有几条语句,运行速度很快的函数,例如:

这个函数的作用只是打印一条分割线,而且在程序中需要被多次调用。相比之下,这种函数被调用的开销就成为了需要考虑的因素了。

inline 关键字

为了减少函数调用的开销,C++引入了内联函数的机制。将函数声明为 inline,表示建议编译器在调用这个函数的时候,将函数的内容展开,此时编译器将会把函数的调用操作改为以一份代码副本来替代。
例如我们要输出100个“生日快乐!”:

#include <iostream>
using namespace std;

void put_a_message();

int main()
{
   for(int i = 0; i < 100; i++)
        put_a_message();
   return 0;
}

inline void put_a_message()
{
    cout << "生日快乐!" << endl;
}

当我们把 put_a_message 函数定义为内联函数时,在内部就可能是以这种方式实现功能:

#include <iostream>
using namespace std;
int main()
{
   for(int i = 0; i < 100; i++)
        cout << "生日快乐!" << endl;
   return 0;
}

使用 inline 的注意事项

1.使用限制

inline 只适合涵数体内代码简单的涵数使用,不能包含复杂的结构控制语句例如 while、switch,并且不能内联函数本身不能是直接递归函数。

2.inline是一个建议

将函数定义为 inline 函数仅仅是对编译器提出的一个要求,编译器不一定执行这项要求,所以最后能否真正内联,看编译器的意思。如果编译器认为函数不复杂,能在调用点展开,就会真正内联,并不是说声明了内联就会内联。

3.适合定义为 inline 的函数

一般来说,最适合定义为内联函数的函数的特点为:体积小、需要被多次调用、执行的操作简单。

4.inline 函数定义

由于内联函数要在被调用的时候展开,所以编译器必须随处可见内联函数的定义,因此 inline 函数的定义常放于头文件。

5.inline 是"用于实现的关键字"

关键字 inline 必须与函数定义体放在一起才能使函数成为内联,仅将 inline 放在函数声明前面不起任何作用。

函数重载

为什么会有“函数重载”

例如我们要写3个函数,分别要求出两个整数,三个整数,两个双精度数的最大值。那么我们把这3和函数都命名为“max”是一件合情合理的事情,但是学习C语言时我们知道不同的函数时不能取相同的函数名的,这就需要我们为这3个函数分别去不同的函数名,甚至会取得又臭又长。

函数重载

我们实现一下前文的代码:

#include <iostream>
using namespace std;
int myMax(int a, int b) 
{
    return (a > b ? a : b);
}

int myMax(int a, int b, int c)
{
    b > a ? a = b : a = a;
    return (a > c ? a : c);
}

double myMax(double a, double b)
{
    return (a > b ? a : b);
}

int main()
{
    cout << myMax(3,4) << endl;
    cout << myMax(3,4,5) << endl;
    cout << myMax(4.3,3.4) << endl;
}

C++允许我们写出好几个具有相同函数名的函数。一个或多个函数名相同,但是函数个数或参数类型不同的函数,叫做函数重载。
函数重载使得函数命名变得简单,在调用函数的时候,编译器会将调用函数时提供的实际参数和每个重载函数的参数对比,判断应该调用哪个函数。

  • 编译器无法根据函数的返回类型来区分两个函数名相同的函数。

函数指针

指向函数的指针

每一个函数都占用一段内存单元,它们有一个起始地址,指向函数入口地址的指针称为函数指针。语法为:

Type (*ptr)(list);
参数 说明
Type 函数的返回值的类型
ptr 指针变量名
list 调用函数时传递的参数表

在函数指针变量赋值时,只需给出函数名,不必给出参数。函数指针变量指向的函数不是固定的,这表示定义了一个这样类型的变量,用来存放函数的入口地址,函数指针指向的函数由我们在程序中把哪一个函数的地址赋给它而决定。

实例


代码实现:

参考资料

《新标准C++程序设计》————郭炜 编著,高等教育出版社
《Essential C++》————[美]Stanley B.Lippman 著,侯捷 译,电子工业出版社
C++里面的iostream是什么
C++构造函数初始化类对象
C++ new和malloc的区别
C++函数指针详解
菜鸟教程
C语言中文网

Guess you like

Origin www.cnblogs.com/linfangnan/p/12294970.html