① Function declaration and definition ② Separate file compilation ③ Pointer definition and use ④ Memory space occupied by pointer

Function can be declared multiple times, but can only be defined once

【the reason】:

The declaration is just to tell the compiler that there is this function

If it is defined multiple times, the compiler does not know which one to run

#include <iostream>
using namespace std;

//函数可以声明多次,但是定义只能有一次
//【理由】:
//声明只是为了告诉编译器有这个函数,而如果定义多次,则让编译器不知道运行哪个

//声明:
int score(int num1, int num2);
int score(int num1, int num2);

//定义:
int score(int num1, int num2)
{
    
    
	int sum = num1 + num2;
	return sum;
}

int main()
{
    
    
	int a = 10;
	int b = 29;
	score(a, b);
	cout << score(a, b) << endl;
	return 0;
}

Sub-document preparation

  • 1. Create a header file with the suffix .h
  • 2. Create a source file with the extension .cpp
  • 3. Write the function declaration in the header file
  • 4. Write the definition of the function in the source file

Other file you want to use the file, only by adding a #include "swap.h" to

【Source File】:

#include "swap.h"
/*  分文件编写
*   1、创建后缀名为 .h 的头文件
*   2、创建后缀名为 .cpp 的源文件
*   3、在头文件中写函数的声明
*   4、在源文件中写函数的定义
* 
其他文件想使用该文件,则只用加一个#include "swap.h"即可
*/
int main()
{
    
    
	int a = 10;
	int b = 20;
	swap(a, b);
	cout << swap(a, b) << endl;
	return 0;
}

【head File】:

#include <iostream>
using namespace std;

int swap(int num1, int num2)
{
    
    
	int sum = num1 + num2;
	return sum;
}

Pointer definition and use

Pointer definition

Data type * pointer variable name;

Use of pointers

Add * in front of the pointer represents dereference , find the data in the memory space pointed to by the pointer

#include <iostream>
using namespace std;

//指针:记录地址编号
   
int main()
{
    
    
	//指针定义
	//数据类型 * 指针变量名;
	int* p;
	int a = 10;
	p = &a;
	cout << p << endl;//a的地址
	cout << *p << endl;//a的值

	//指针的使用
	//指针前面加*代表解引用,找到指针指向的内存空间的数据
	*p = 1000;
	cout << p << endl;//a的地址
	cout << *p << endl;//更新的值
	return 0;
}

Memory space occupied by pointers

A pointer is 4 bytes of memory space in a 32-bit operating system ( regardless of the data type )

#include <iostream>
using namespace std;

int main(){
    
    
    //指针在32位操作系统中是4个字节的内存空间(无论什么的数据类型)
	cout << sizeof(int*) << endl;
	cout << sizeof(float*) << endl;
	cout << sizeof(long*) << endl;
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_42198265/article/details/113752669