Cpp_part1

Cpp_part1

Charles Lv7

这个专题是对Pre_OO课程的记录

1.Struct 结构体

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// A better C
// array ,pointer(dynamic memory allocation malloc/free stack/heap),
// function(pfn 函数指针 bsearch,qsort),struct,macro
// struct
// #pragma pack(1)//取消对齐
struct Test1 {
int i;
double d;
int j;
};
// sizeof(Test)为24,因为内存对齐
struct Test2 {
int i, j;
double d;
};
// sizeof(Test)为24,因为内存对齐
struct Test3 { //位结构
char a1 : 1;
int a2 : 2;
};

2.Macro 宏

1
2
3
4
5
6
7
8
// 1.常量宏
#define PI 3.14
#define STU_CNT 200
// 2.函数宏
#define ARRAY_SIZE(a) sizeof(a) / sizeof(a[0])
#define ADD(a, b) a + b
// 3.控制宏,开关
#define LOCAL_VER

3.C++如何调用C函数

1
2
3
4
5
6
7
8
9
#ifdef __cplusplus
extern "C" {
#endif
void mod5();
#ifdef __cplusplus
}
#endif
//一个不太友好的写法
extern "C" void mod5();

4.函数重载

函数重载:同名函数,不同参数,不能靠不同返回值

1
2
3
4
5
6
void print(int i) {
cout << i << endl;
}
void print(string str) {
cout << str << endl;
}

5.默认参数

1
2
3
int fun(int a, int b = 10, int c = 20) {
return a + b + c;
}

Main part

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <bits/stdc++.h>
using namespace std;
#ifdef WIN32
#include <windows.h>
#endif
int main(int argc, char* argv[]) {
cout << sizeof(Test1) << endl;
cout << sizeof(Test2) << endl;
cout << sizeof(Test3) << endl;
cout << ADD(3, 4) * 2 << endl;
#ifdef LOCAL_VER
cout << "LOCAL_VER" << endl;
#else
cout << "oracle" << endl;
#endif
mod5();
print("hello world");
cout << fun(10) << endl;
return 0;
}

//mod.c
#include <stdio.h>
void mod5() {
printf("extern function");
}
  • Title: Cpp_part1
  • Author: Charles
  • Created at : 2022-12-28 07:59:40
  • Updated at : 2023-02-09 17:56:59
  • Link: https://charles2530.github.io/2022/12/28/cpp-part1/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments