C++学习笔记

2023-10-15后端15 分钟121 次阅读
AI 摘要鱼粮不足,AI 今天先歇着 · 正文在下面

一、基本语法

1、基本的输入与输出

头文件 函数和描述
<iostream> 该文件定义了 cin、cout、cerr 和 clog 对象,分别对应于标准输入流、标准输出流、非缓冲标准错误流和缓冲标准错误流。
<iomanip> 该文件通过所谓的参数化的流操纵器(比如 setw 和 setprecision),来声明对执行标准化 I/O 有用的服务。
<fstream> 该文件为用户控制的文件处理声明服务。我们将在文件和流的相关章节讨论它的细节。

标准输出流(cout)

预定义的对象 cout 是 iostream 类的一个实例。cout 对象"连接"到标准输出设备,通常是显示屏。cout 是与流插入运算符 << 结合使用的,如下所示:

c++ 复制代码
#include <iostream>
using namespace std;

int main() {
    char str[] = "Hello C++";
    cout << "Value of str is : " << str << endl;
}

标准输入流(cin)

预定义的对象 cin 是 iostream 类的一个实例。cin 对象附属到标准输入设备,通常是键盘。cin 是与流提取运算符 >> 结合使用的,如下所示:

c++ 复制代码
#include <iostream>
using namespace std;

int main() {
    char name[50];
    cout << "请输入您的名称: ";
    cin >> name;
    cout << "您的名称是: " << name << endl;
}

标准错误流(cerr)

预定义的对象 cerr 是 iostream 类的一个实例。cerr 对象附属到标准输出设备,通常也是显示屏,但是 cerr 对象是非缓冲的,且每个流插入到 cerr 都会立即输出。

cerr 也是与流插入运算符 << 结合使用的,如下所示:

c++ 复制代码
#include <iostream>
using namespace std;

int main() {
    char str[] = "Unable to read....";
    cerr << "Error message : " << str << endl;
}

标准日志流(clog)

预定义的对象 clog 是 iostream 类的一个实例。clog 对象附属到标准输出设备,通常也是显示屏,但是 clog 对象是缓冲的。这意味着每个流插入到 clog 都会先存储在缓冲区,直到缓冲填满或者缓冲区刷新时才会输出。

clog 也是与流插入运算符 << 结合使用的,如下所示:

c++ 复制代码
#include <iostream>
using namespace std;

int main() {
    char str[] = "Unable to read....";
    clog << "Error message : " << str << endl;
}

2、注释

c++ 复制代码
void exegesis() {
    // 单行注释
    /*多行注释*/

    // 条件编译
#if condition
    cout << "func1";
# else
    cout << "func2";
# endif
}

3、基本内置类型

c++ 复制代码
void datatype() {
    bool b = true;
    cout << "bool: " << b << endl;

    char c = 'a';
    cout << "char: " << c << endl;

    int i = 12;
    cout << "int: " << i << endl;

    float f = 10.0f;
    cout << "float: " << f << endl;

    double d = 11.24654;
    cout << "double: " << d << endl;

    string s = "Hello, World!";
    cout << "string: " << s << endl;

//    void // 无类型;

//    char cc='哈'; 普通char类型无法存储汉字,汉字占双字节
    setlocale(LC_ALL, "chs"); //转换为中文字符

    //宽字符型,可用于存汉字
    //wchar_t wt = L'哈';
    //wcout << "wchar_t: " << wt << endl;
}

4、typedef声明

c++ 复制代码
// 给一个已有类型取新的名字,这里int的另一个名称是Integer
typedef int Integer;
Integer num_test = 1;

5、枚举类型

c++ 复制代码
// 定义一个颜色枚举,默认情况下第一个名称的值为0,第二个为1,以此来推,
// 这里给了green的值为5,所以blue的值为6
enum ColorType {
    red, green = 5, blue
};

// 使用枚举
void useEnum() {
    // 声明并初始化枚举变量
    ColorType color = ColorType::red;

    // 使用枚举变量进行其他操作
    if (color == ColorType::red) {
        cout << "The color is red." << endl;
    } else if (color == ColorType::green) {
        cout << "The color is green." << endl;
    } else if (color == ColorType::blue) {
        cout << "The color is blue." << endl;
    } else {
        cout << "Unknown color." << endl;
    }
}

6、类型转换

c++ 复制代码
void typeConversion() {
    // 静态转换
    // 静态转换是将一种数据类型的值强制转换为另一种数据类型的值。
    // 静态转换通常用于比较类型相似的对象之间的转换,例如将 int 类型转换为 float 类型。
    // 静态转换不进行任何运行时类型检查,因此可能会导致运行时错误。
    int a = 10;
    double b = static_cast<double>(a); // 将整数a转换为双精度浮点数b
//    double b = (double) a;
    cout << "Static Conversion: " << b << endl;

    // 动态转换
    // 动态转换通常用于将一个基类指针或引用转换为派生类指针或引用。
    // 动态转换在运行时进行类型检查,如果不能进行转换则返回空指针或引发异常。
    class Base {
    public:
        virtual ~Base() {} // 添加虚析构函数
    };
    class Derived : public Base {
    };
    Base *ptr_base = new Derived;
    Derived *ptr_derived = dynamic_cast<Derived *>(ptr_base); // 将基类指针转换为派生类指针
    cout << "Dynamic Conversion: " << ptr_derived << endl;

    // 常量转换
    // 常量转换用于将 const 类型的对象转换为非 const 类型的对象。
    // 常量转换只能用于转换掉 const 属性,不能改变对象的类型。
    const int e = 5;
    int i = const_cast<int &>(e); // 常量转换,将const int转换为int
    cout << "Constant Conversion: " << i << endl;

    // 重新解释转换
    // 重新解释转换将一个数据类型的值重新解释为另一个数据类型的值,通常用于在不同的数据类型之间进行转换。
    // 重新解释转换不进行任何类型检查,因此可能会导致未定义的行为。
    int ii = 10;
    float h = reinterpret_cast<float &>(ii); // 重新解释将int类型转换为float类型
    cout << "Reinterpretation Conversion: " << h << endl;
}

7、变量

c++ 复制代码
// 变量声明
extern int a, b;
extern int c;
extern float f;

// 变量
void variable() {
    // 变量定义
    int a, b;
    int c;
    float f;

    // 实际初始化
    a = 10;
    b = 20;
    c = a + b;

    cout << c << endl;

    f = 70.0 / 3.0;
    cout << f << endl;
}

8、函数声明

c++ 复制代码
//函数声明
void print();

int main() {
    // 函数调用
    print();
    return 0;
}
// 定义函数
void print() {
    cout << "Hello World" << endl;
}

9、类作用域

c++ 复制代码
// 类作用域
class MyClass {
public:
    // 声明了一个名为 class_var 的类作用域变量
    static int class_var;
};

// 类名和作用域解析运算符 :: 来访问这个变量
int MyClass::class_var = 30;

// 类作用域
void classScope() {
    cout << "类变量: " << MyClass::class_var << endl;
}

10、常量

c++ 复制代码
// 常量 
// 常量是固定值,在程序执行期间不会改变。这些固定的值,又叫做字面量。
// 使用 #define 预处理器定义常量的形式
#define LENGTH 10
#define WIDTH  5

void constant() {
    cout << "常量长度: " << LENGTH << endl;
    cout << "常量宽度: " << WIDTH << endl;
    // const 前缀声明指定类型的常量
    const int area = WIDTH * LENGTH;
    cout << "常量面积: " << area << endl;
}

11、循环

c++ 复制代码
// 循环
void circulation() {
    // while 循环
    int count = 0;
    while (count < 3) {
        cout << "while 循环 count 的值:" << count << endl;
        count++;
    }

    // for 循环
    count = 0;
    for (int i = 0; i < 5; i++) {
        cout << "for 循环 i 的值:" << i << endl;
    }

    int my_array[5] = {1, 2, 3, 4, 5};
    // 每个数组元素乘于 2
    for (int &x: my_array) {
        x *= 2;
        cout << "增强 for 循环 x 的值:" << x << endl;
    }
    // auto 类型也是 C++11 新标准中的,用来自动获取变量的类型
    for (auto &x: my_array) {
        x *= 2;
        cout << "auto 增强 for 循环 x 的值:" << x << endl;
    }
    string str("some string");
    // range for 语句
    for (auto &c: str) {
        c = toupper(c);
    }
    cout << "转换为大写后的字符串:" << str << endl;

    // do...while
    // 局部变量声明
    int aa = 10;
    // do 循环执行
    do {
        cout << " do...while aa 的值:" << aa << endl;
        aa = aa + 1;
    } while (aa < 20);

}

12、判断

c++ 复制代码
void conditionalJudgment() {
    int i;
    cout << "请输入数字:" << endl;
    scanf("%d", &i);
    if (i == 0) {
        cout << "i等于0" << endl;
    } else if (i > 0) {
        cout << "i为正数" << endl;
    } else {
        cout << "i为负数" << endl;
    }
    // 条件运算符? :
    i == 0 ? cout << "i等于0" << endl : cout << "i不等于0" << endl;


    // 局部变量声明
    char grade = 'A';
    switch (grade) {
        case 'A' :
            cout << "很棒!" << endl;
            break;
        case 'B' :
        case 'C' :
            cout << "做得好" << endl;
            break;
        case 'D' :
            cout << "您通过了" << endl;
            break;
        case 'F' :
            cout << "最好再试一下" << endl;
            break;
        default :
            cout << "无效的成绩" << endl;
    }
    cout << "您的成绩是 " << grade << endl;
}

13、函数

c++ 复制代码
#include <iostream>
using namespace std;

// 函数声明
int max(int num1, int num2);
void swap(int *x, int *y);
void swap(int &x, int &y);

int main() {
    // 局部变量声明
    int a = 100;
    int b = 200;
    int ret;

    // 传值调用函数来获取最大值
    ret = max(a, b);
    cout << "Max value is : " << ret << endl;

    cout << "交换前,a 的值:" << a << endl;
    cout << "交换前,b 的值:" << b << endl;

    /* 调用函数来交换值
     * &a 表示指向 a 的指针,即变量 a 的地址
     * &b 表示指向 b 的指针,即变量 b 的地址
     */
    swap(&a, &b);

    cout << "指针调用交换后,a 的值:" << a << endl;
    cout << "指针调用交换后,b 的值:" << b << endl;

    /* 调用函数来交换值 */
    swap(a, b);

    cout << "引用调用交换后,a 的值:" << a << endl;
    cout << "引用调用交换后,b 的值:" << b << endl;

    return 0;
}
// 传值调用
int max(int num1, int num2) {
    // 局部变量声明
    int result;
    if (num1 > num2)
        result = num1;
    else
        result = num2;
    return result;
}

// 指针调用
void swap(int *x, int *y) {
    int temp;
    temp = *x;    /* 保存地址 x 的值 */
    *x = *y;        /* 把 y 赋值给 x */
    *y = temp;    /* 把 x 赋值给 y */
}

// 引用调用
void swap(int &x, int &y) {
    int temp;
    temp = x; /* 保存地址 x 的值 */
    x = y;    /* 把 y 赋值给 x */
    y = temp; /* 把 x 赋值给 y  */
}

14、数字

c++ 复制代码
#include <cmath>

// 使用数学运算
void useMath() {
    // 数字定义
    short s = 10;
    int i = -1000;
    long l = 100000;
    float f = 230.47;
    double d = 200.374;

    // 数学运算
    cout << "sin(d) :" << sin(d) << endl;
    cout << "abs(i)  :" << abs(i) << endl;
    cout << "floor(d) :" << floor(d) << endl;
    cout << "sqrt(f) :" << sqrt(f) << endl;
    cout << "pow( d, 2) :" << pow(d, 2) << endl;
}

#include <cstdlib>
#include <ctime>

// 使用随机数
void useRandom() {
    int i, j;

    // 设置种子
    srand((unsigned) time(NULL));
    /* 生成 10 个随机数 */
    for (i = 0; i < 10; i++) {
        // 生成实际的随机数
        j = rand();
        cout << "随机数: " << j << endl;
    }
}

15、数组

c++ 复制代码
void useArray() {
    // 一维数组
    int n[10]; // n 是一个包含 10 个整数的数组
    // 初始化数组元素
    for (int i = 0; i < 10; i++) {
        n[i] = i + 100; // 设置元素 i 为 i + 100
    }
    cout << "Element" << setw(13) << "Value" << endl;
    // 输出数组中每个元素的值
    for (int j = 0; j < 10; j++) {
        cout << setw(7) << j << setw(13) << n[j] << endl;
    }

    // 二维数组
    int a[3][4] = {
            {0, 1, 2,  3},   /*  初始化索引号为 0 的行 */
            {4, 5, 6,  7},   /*  初始化索引号为 1 的行 */
            {8, 9, 10, 11}   /*  初始化索引号为 2 的行 */
    };
    // int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11}; // 上面是等同的
    // 输出数组中每个元素的值
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 4; j++) {
            cout << "a[" << i << "][" << j << "]: ";
            cout << a[i][j] << endl;
        }
    }

    // 指向数组的指针
    // 带有 5 个元素的双精度浮点型数组
    double array[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
    double *p;
    p = array;
    // 输出数组中每个元素的值
    cout << "使用指针的数组值 " << endl;
    for (int i = 0; i < 5; i++) {
        cout << "*(p + " << i << ") : ";
        cout << *(p + i) << endl;
    }
    cout << "使用 array 作为地址的数组值 " << endl;
    for (int i = 0; i < 5; i++) {
        cout << "*(array + " << i << ") : ";
        cout << *(array + i) << endl;
    }


}

// 形式参数是一个指针
void myFunction1(int *param) {
}

// 形式参数是一个已定义大小的数组
void myFunction2(int param[10]) {
}

// 形式参数是一个未定义大小的数组
void myFunction3(int param[]) {
}

16、字符串

C++ 中有大量的函数用来操作以 null 结尾的字符串:

序号 函数 & 目的
1 strcpy(s1, s2);
复制字符串 s2 到字符串 s1。
2 strcat(s1, s2);
连接字符串 s2 到字符串 s1 的末尾。连接字符串也可以用 + 号,例如:
string str1 = "salmon";
string str2 = "google";
string str = str1 + str2;
3 strlen(s1);
返回字符串 s1 的长度。
4 strcmp(s1, s2);
如果 s1 和 s2 是相同的,则返回 0;如果 s1<s2 则返回值小于 0;如果 s1>s2 则返回值大于 0。
5 strchr(s1, ch);
返回一个指针,指向字符串 s1 中字符 ch 的第一次出现的位置。
6 strstr(s1, s2);
返回一个指针,指向字符串 s1 中字符串 s2 的第一次出现的位置。
c++ 复制代码
#include <string>

void useString() {
    char site[7] = {'S', 'A', 'L', 'M', 'O', 'N', '\0'};
    // char site[] = "SALMON"; //依据数组初始化规则,您可以把上面的语句写成该语句
    cout << "Salmon教程: ";
    cout << site << endl;

    char str1[13] = "salmon";
    char str2[13] = "google";
    char str3[13];
    int len;

    // 复制 str1 到 str3
    strcpy(str3, str1);
    cout << "strcpy( str3, str1) : " << str3 << endl;

    // 连接 str1 和 str2
    strcat(str1, str2);
    cout << "strcat( str1, str2): " << str1 << endl;

    // 连接后,str1 的总长度
    len = strlen(str1);
    cout << "strlen(str1) : " << len << endl;

    cout << "string-------" << endl;

    // string
    string str11 = "salmon";
    string str22 = "google";
    string str33;
    int length;

    // 复制 str1 到 str3
    str33 = str11;
    cout << "str33 : " << str33 << endl;

    // 连接 str11 和 str22
    str33 = str11 + str22;
    cout << "str11 + str22 : " << str33 << endl;

    // 连接后,str3 的总长度
    length = str33.size();
    cout << "str33.size() :  " << length << endl;

}

17、指针

基本使用

c++ 复制代码
int main() {
    cout << "地址------" << endl;
    int var1;
    char var2[10];

    cout << "var1 变量的地址: ";
    cout << &var1 << endl;

    cout << "var2 变量的地址: ";
    cout << &var2 << endl;

    // 指针的使用
    cout << "指针的使用------" << endl;
    int var = 20;   // 实际变量的声明
    int *ip;        // 指针变量的声明

    ip = &var;       // 在指针变量中存储 var 的地址

    cout << "Value of var variable: ";
    cout << var << endl;

    // 输出在指针变量中存储的地址
    cout << "Address stored in ip variable: ";
    cout << ip << endl;

    // 访问指针中地址的值
    cout << "Value of *ip variable: ";
    cout << *ip << endl;

    // 空指针
    cout << "空指针------" << endl;
    int *ptr = NULL;
    // 这里输出0,内存地址 0 有特别重要的意义
    // 它表明该指针不指向一个可访问的内存位置。
    // 但按照惯例,如果指针包含空值(零值),则假定它不指向任何东西。
    cout << "ptr 的值是 " << ptr << endl;
    // 如需检查一个空指针,您可以使用 if 语句,如下所示:
    if (ptr) {/* 如果 ptr 非空,则完成 */}
    if (!ptr) {   /* 如果 ptr 为空,则完成 */}
}

算术运算

c++ 复制代码
const int MAX = 3;

int main() {
    cout << "算术运算------" << endl;
    int var11[MAX] = {10, 100, 200};
    int *ptr1;

    // 递增一个指针
    cout << "递增一个指针:" << endl;
    // 指针中的数组地址
    ptr1 = var11;
    for (int i = 0; i < MAX; i++) {
        cout << "Address of var[" << i << "] = ";
        cout << ptr1 << endl;

        cout << "Value of var[" << i << "] = ";
        cout << *ptr1 << endl;

        // 移动到下一个位置
        ptr1++;
    }

    // 递减一个指针
    cout << "递减一个指针:" << endl;
    // 指针中最后一个元素的地址
    ptr1 = &var11[MAX - 1];
    for (int i = MAX; i > 0; i--) {
        cout << "Address of var[" << i << "] = ";
        cout << ptr1 << endl;

        cout << "Value of var[" << i << "] = ";
        cout << *ptr1 << endl;

        // 移动到下一个位置
        ptr1--;
    }


    // 指针的比较
    cout << "指针的比较:" << endl;
    // 指针中第一个元素的地址
    ptr1 = var11;
    int i = 0;
    while (ptr1 <= &var11[MAX - 1]) {
        cout << "Address of var[" << i << "] = ";
        cout << ptr1 << endl;

        cout << "Value of var[" << i << "] = ";
        cout << *ptr1 << endl;

        // 指向上一个位置
        ptr1++;
        i++;
    }
}

指针与数组

c++ 复制代码
const int MAX = 3;

int main() {
    // 指针与数组的一些操作区别
    int var[MAX] = {10, 100, 200};

    for (int i = 0; i < MAX; i++) {
        *var = i;    // 这是正确的语法
//        var++;       // 这是不正确的 var如果是指针,才可以做++操作,例如 int *ptr,则可以ptr++
    }

    *(var + 2) = 500;
    cout << "修改后的var[2]的值为:" << var[2] << endl;

    // 指针数组
    int var1[MAX] = {10, 100, 200};

    for (int i = 0; i < MAX; i++) {
        cout << "Value of var1[" << i << "] = ";
        cout << var1[i] << endl;
    }

    int *ptr[MAX];
    for (int i = 0; i < MAX; i++) {
        ptr[i] = &var1[i]; // 赋值为整数的地址
    }
    for (int i = 0; i < MAX; i++) {
        cout << "Value of var1[" << i << "] = ";
        cout << *ptr[i] << endl;
    }

    // 用一个指向字符的指针数组来存储一个字符串列表,如下
    const int MAX1 = 4;
    const char *names[MAX1] = {
            "Zara Ali",
            "Hina Ali",
            "Nuha Ali",
            "Sara Ali",
    };

    for (int i = 0; i < MAX1; i++) {
        cout << "Value of names[" << i << "] = ";
        cout << names[i] << endl;
    }
}

指向指针的指针

c++ 复制代码
int main() {
    int var;
    int *ptr;
    int **pptr;

    var = 3000;

    // 获取 var 的地址
    ptr = &var;

    // 使用运算符 & 获取 ptr 的地址
    pptr = &ptr;

    // 使用 pptr 获取值
    cout << "var 值为 :" << var << endl;
    cout << "*ptr 值为:" << *ptr << endl;
    cout << "**pptr 值为:" << **pptr << endl;
}

函数返回指针

c++ 复制代码
#include <iostream>
#include <ctime>
#include <cstdlib>
 
using namespace std;
 
// 要生成和返回随机数的函数
int * getRandom( )
{
  static int  r[10];
 
  // 设置种子
  srand( (unsigned)time( NULL ) );
  for (int i = 0; i < 10; ++i)
  {
    r[i] = rand();
    cout << r[i] << endl;
  }
 
  return r;
}
 
// 要调用上面定义函数的主函数
int main ()
{
   // 一个指向整数的指针
   int *p;
 
   p = getRandom();
   for ( int i = 0; i < 10; i++ )
   {
       cout << "*(p + " << i << ") : ";
       cout << *(p + i) << endl;
   }
 
   return 0;
}

18、日期&时间

c++ 复制代码
#include <ctime>
#include <cstdio>
#include <unistd.h>

#define BST (+1)
#define CCT (+8)

void useTime() {
    time_t seconds;
    seconds = time(NULL);
    printf("time()=======根据返回值 自 1970-01-01 起的小时数 = %ld\n", seconds / 3600);
    // 基于当前系统的当前日期/时间
    time_t now = time(0);
    cout << "time()=======1970 到目前经过秒数:" << now << endl;
}

// ctime()
// 返回一个表示当地时间的字符串,当地时间是基于参数 timer。
// 返回的字符串格式如下: Www Mmm dd hh:mm:ss yyyy
// 其中,Www 表示星期几,Mmm 是以字母表示的月份,dd 表示一月中的第几天,hh:mm:ss 表示时间,yyyy 表示年份
void useCtime() {
    time_t now = time(0);
    // 把 now 转换为字符串形式
    char *dt = ctime(&now);
    cout << "ctime()=======本地日期和时间:" << dt << endl;
}

// localtime()
// 使用 timer 的值来填充 tm 结构。timer 的值被分解为 tm 结构,并用本地时区表示
void useLocaltime() {
    time_t now = time(0);
    time_t *rawtime;
    struct tm *info;
    time(rawtime);
    info = localtime(rawtime);
    printf("localtime()=======当前的本地时间和日期:%s", asctime(info));
    tm *ltm = localtime(&now);
    // 输出 tm 结构的各个组成部分
    cout << "localtime()=======年: " << 1900 + ltm->tm_year << endl;
    cout << "localtime()=======月: " << 1 + ltm->tm_mon << endl;
    cout << "localtime()=======日: " << ltm->tm_mday << endl;
    cout << "localtime()=======时间: " << ltm->tm_hour << ":";
    cout << ltm->tm_min << ":";
    cout << ltm->tm_sec << endl;
}

// clock()
// 返回程序执行起(一般为程序的开头),处理器时钟所使用的时间。
// 为了获取 CPU 所使用的秒数,您需要除以 CLOCKS_PER_SEC。
// 在 32 位系统中,CLOCKS_PER_SEC 等于 1000000,该函数大约每 72 分钟会返回相同的值
void useClock() {
    clock_t start_t, end_t;
    double total_t;
    int i;
    start_t = clock();
    printf("clock()=======开始一个大循环,start_t = %ld\n", start_t);
    for (i = 0; i < 10000000; i++) {
    }
    end_t = clock();
    printf("clock()=======大循环结束,end_t = %ld\n", end_t);
    total_t = (double) (end_t - start_t) / CLOCKS_PER_SEC;
    printf("clock()=======CPU 占用的总时间:%f\n", total_t);
}

// gmtime()
// 使用 timer 的值来填充 tm 结构,并用协调世界时(UTC)也被称为格林尼治标准时间(GMT)表示
// 把 now 转换为 tm 结构
void useGmtime() {
    time_t rawtime;
    time(&rawtime);
    tm *info = gmtime(&rawtime);
    printf("gmtime()=======当前的世界时钟:\n");
    printf("gmtime()=======伦敦:%2d:%02d\n", (info->tm_hour + BST) % 24, info->tm_min);
    printf("gmtime()=======中国:%2d:%02d\n", (info->tm_hour + CCT) % 24, info->tm_min);
}

// asctime
// 一个指向字符串的指针,它代表了结构 struct timeptr 的日期和时间
void useAsctime() {
    time_t rawtime;
    time(&rawtime);
    tm *info = gmtime(&rawtime);
    // 一个指向字符串的指针,它代表了结构 struct timeptr 的日期和时间
    char *dt1 = asctime(info);
    cout << "asctime()=======UTC 日期和时间:" << dt1 << endl;
    struct tm t;
    t.tm_sec = 10;
    t.tm_min = 10;
    t.tm_hour = 6;
    t.tm_mday = 25;
    t.tm_mon = 2;
    t.tm_year = 89;
    t.tm_wday = 6;
    puts(asctime(&t));
}

// mktime()
// 把 timeptr 所指向的结构转换为自 1970 年 1 月 1 日以来持续时间的秒数,发生错误时返回-1。
void useMkTime() {
    time_t rawtime2;
    struct tm *timeinfo;
    int year, month, day;
    const char *weekday[] = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
    /* 用户输入日期 */
    printf("mktime()=======年: ");
    fflush(stdout);
    scanf("%d", &year);
    printf("mktime()=======月: ");
    fflush(stdout);
    scanf("%d", &month);
    printf("mktime()=======日: ");
    fflush(stdout);
    scanf("%d", &day);

    /* 获取当前时间信息,并修改用户输入的输入信息 */
    time(&rawtime2);
    timeinfo = localtime(&rawtime2);
    timeinfo->tm_year = year - 1900;
    timeinfo->tm_mon = month - 1;
    timeinfo->tm_mday = day;

    /* 调用 mktime: timeinfo->tm_wday  */
    mktime(timeinfo);

    printf("mktime()=======那一天是:%s\n", weekday[timeinfo->tm_wday]);
}

// difftime()
// 返回 time1 和 time2 之间相差的秒数 (time1 - time2)。
// 这两个时间是在日历时间中指定的,表示了自纪元 Epoch(协调世界时 UTC:1970-01-01 00:00:00)起经过的时间。
void useDifftime() {
    time_t start_t, end_t;
    double diff_t;

    printf("difftime()=======程序启动...\n");
    time(&start_t);

    printf("difftime()=======休眠 5 秒...\n");
    sleep(5);

    time(&end_t);
    diff_t = difftime(end_t, start_t);

    printf("difftime()=======执行时间 = %f\n", diff_t);
    printf("difftime()=======程序退出...\n");
}

// strftime()
// 根据 format 中定义的格式化规则,格式化结构 timeptr 表示的时间,并把它存储在 str 中。
void useStrftime() {
    time_t rawtime;
    struct tm *info;
    char buffer[80];

    time(&rawtime);

    info = localtime(&rawtime);

    strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", info);
    printf("格式化的日期 & 时间 : |%s|\n", buffer);
}


// 使用日期&时间
void useStudyTime() {
    // time()
    useTime();
    // ctime()
    useCtime();
    // localtime()
    useLocaltime();
    // clock()
    useClock();
    // gmtime()
    useGmtime();
    // asctime()
    useAsctime();
    // mktime()
    useMkTime();
    // difftime()
    useDifftime();
    // strftime()
    useStrftime();
}

19、引用

c++ 复制代码
// 引用
// 引用很容易与指针混淆,它们之间有三个主要的不同:
// 1.不存在空引用。引用必须连接到一块合法的内存。
// 2.一旦引用被初始化为一个对象,就不能被指向到另一个对象。指针可以在任何时候指向到另一个对象。
// 3.引用必须在创建时被初始化。指针可以在任何时间被初始化。
void useReference() {
    // 声明简单的变量
    int i;
    double d;

    // 声明引用变量
    int &r = i;
    double &s = d;

    i = 5;
    cout << "Value of i : " << i << endl;
    cout << "Value of i reference : " << r << endl;

    d = 11.7;
    cout << "Value of d : " << d << endl;
    cout << "Value of d reference : " << s << endl;
}

20、数据结构

结构是 C++ 中一种用户自定义的可用的数据类型,它允许您存储不同类型的数据项。

结构作为函数参数

c++ 复制代码
#include <cstring>
#include <iostream>

using namespace std;

// 声明一个结构体类型 Books
struct Books {
    char title[50];
    char author[50];
    char subject[100];
    int book_id;
};

// 输出结构体
void printBook(struct Books book) {
    cout << "书标题 : " << book.title << endl;
    cout << "书作者 : " << book.author << endl;
    cout << "书类目 : " << book.subject << endl;
    cout << "书 ID : " << book.book_id << endl;
}

void main() {
    Books Book1;        // 定义结构体类型 Books 的变量 Book1
    Books Book2;        // 定义结构体类型 Books 的变量 Book2

    // Book1 详述
    strcpy(Book1.title, "C++ 教程");
    strcpy(Book1.author, "Salmon");
    strcpy(Book1.subject, "编程语言");
    Book1.book_id = 12345;

    // Book2 详述
    strcpy(Book2.title, "Java 教程");
    strcpy(Book2.author, "Salmon");
    strcpy(Book2.subject, "编程语言");
    Book2.book_id = 12346;

    // 输出 Book1 信息
    printBook(Book1);

    // 输出 Book2 信息
    printBook(Book2);
}

指向结构的指针

c++ 复制代码
void printBook(struct Books *book);

void main() {
    Books Book1;        // 定义结构体类型 Books 的变量 Book1
    Books Book2;        // 定义结构体类型 Books 的变量 Book2

    // Book1 详述
    strcpy(Book1.title, "C++ 教程");
    strcpy(Book1.author, "Salmon");
    strcpy(Book1.subject, "编程语言");
    Book1.book_id = 12345;

    // Book2 详述
    strcpy(Book2.title, "Java 教程");
    strcpy(Book2.author, "Salmon");
    strcpy(Book2.subject, "编程语言");
    Book2.book_id = 12346;

    // 通过传 Book1 的地址来输出 Book1 信息
    printBook(&Book1);

    // 通过传 Book2 的地址来输出 Book2 信息
    printBook(&Book2);
}

// 该函数以结构指针作为参数
void printBook(struct Books *book) {
    cout << "书标题  : " << book->title << endl;
    cout << "书作者 : " << book->author << endl;
    cout << "书类目 : " << book->subject << endl;
    cout << "书 ID : " << book->book_id << endl;
}

typedef 关键字

为创建的类型取一个"别名",这样可以直接使用 Books 来定义 Books 类型的变量,而不需要使用 struct 关键字

c++ 复制代码
typedef struct Books
{
   char  title[50];
   char  author[50];
   char  subject[100];
   int   book_id;
}Books;

二、面向对象

1、类&对象

C++ 在 C 语言的基础上增加了面向对象编程,C++ 支持面向对象程序设计。类是 C++ 的核心特性,通常被称为用户定义的类型。

类用于指定对象的形式,是一种用户自定义的数据类型,它是一种封装了数据和函数的组合。类中的数据称为成员变量,函数称为成员函数。类可以被看作是一种模板,可以用来创建具有相同属性和行为的多个对象。

类定义

定义一个类需要使用关键字 class,然后指定类的名称,并类的主体是包含在一对花括号中,主体包含类的成员变量和成员函数。

定义一个类,本质上是定义一个数据类型的蓝图,它定义了类的对象包括了什么,以及可以在这个对象上执行哪些操作
image.png
示例

c++ 复制代码
#include <iostream>

using namespace std;

class Box {
public:
    double length;   // 盒子的长度
    double breadth;  // 盒子的宽度
    double height;   // 盒子的高度
    // 成员函数声明
    double getVolume(void);

    void set(double len, double bre, double hei);
};

void Box::set(double len, double bre, double hei) {
    length = len;
    breadth = bre;
    height = hei;
}

double Box::getVolume(void) {
    return length * breadth * height;
}

int main() {
    Box Box1;        // 声明 Box1,类型为 Box
    Box Box2;        // 声明 Box2,类型为 Box
    Box Box3;        // 声明 Box3,类型为 Box
    double volume = 0.0;     // 用于存储体积

    // box 1 详述
    Box1.height = 5.0;
    Box1.length = 6.0;
    Box1.breadth = 7.0;

    // box 2 详述
    Box2.height = 10.0;
    Box2.length = 12.0;
    Box2.breadth = 13.0;

    // box 1 的体积
    volume = Box1.height * Box1.length * Box1.breadth;
    cout << "Box1 的体积:" << volume << endl;

    // box 2 的体积
    volume = Box2.height * Box2.length * Box2.breadth;
    cout << "Box2 的体积:" << volume << endl;


    // box 3 详述
    Box3.set(16.0, 8.0, 12.0);
    volume = Box3.getVolume();
    cout << "Box3 的体积:" << volume << endl;
}

类成员函数

c++ 复制代码
#include <iostream>

using namespace std;

class Box {
public:
    double length;         // 长度
    double breadth;        // 宽度
    double height;         // 高度

    // 成员函数声明
    double getVolume(void);

    void setLength(double len);

    void setBreadth(double bre);

    void setHeight(double hei);
};

// 成员函数定义
double Box::getVolume(void) {
    return length * breadth * height;
}

void Box::setLength(double len) {
    length = len;
}

void Box::setBreadth(double bre) {
    breadth = bre;
}

void Box::setHeight(double hei) {
    height = hei;
}

// 程序的主函数
int main() {
    Box Box1;                // 声明 Box1,类型为 Box
    Box Box2;                // 声明 Box2,类型为 Box
    double volume = 0.0;     // 用于存储体积

    // box 1 详述
    Box1.setLength(6.0);
    Box1.setBreadth(7.0);
    Box1.setHeight(5.0);

    // box 2 详述
    Box2.setLength(12.0);
    Box2.setBreadth(13.0);
    Box2.setHeight(10.0);

    // box 1 的体积
    volume = Box1.getVolume();
    cout << "Box1 的体积:" << volume << endl;

    // box 2 的体积
    volume = Box2.getVolume();
    cout << "Box2 的体积:" << volume << endl;
    return 0;
}

类访问修饰符

数据封装是面向对象编程的一个重要特点,它防止函数直接访问类类型的内部成员。类成员的访问限制是通过在类主体内部对各个区域标记public、private、protected来指定的。关键字public、private、protected称为访问修饰符。

c++ 复制代码
class Base {
public:
    // 公有成员
    
protected:
    // 受保护成员

private:
    // 私有成员
};
觉得有用就点个赞,不用登录也能读

评论

0 条
登录 之后才能评论
—
还没有评论,来说第一句