C++基础复习1

#include 
#include 



using namespace std;


// 值传递,形参的修改是影响不了实参
void swap1(int a, int b) {
    int temp;
    temp = a;
    a = b;
    b = temp;
}


// 地址传递,修改形参会影响实参
void swap2(int* p, int* q) {
    int temp;
    temp = *p;
    *p = *q;
    *q = temp;
}



struct student
{
    string name;
    int age;
    int score;
}stu2;  // 创建结构体变量stu2


int main() {

    int num1 = 1, num2 = 100;
    swap1(num1, num2);
    cout << "num1 = " << num1 << "  num2 = " << num2 << endl;
    

    swap2(&num1, &num2);
    cout << "num1 = " << num1 << "   num2 = " << num2 << endl;
    


    int a = 10;
    int *q;
    q = &a;
    
    cout << "&a = " << &a << endl;
    cout << "q = " << q << endl;

    // 解引用
    cout << "*q = " << *q << endl;

    // 指针类型占8个byte
    cout << sizeof(q) << endl;
    cout << sizeof(int*) << endl;
    cout << sizeof(float*) << endl;

    // 空指针
    int *p = nullptr;
    // 直接访问空指针会报错
    //cout << *p << endl;

    // 野指针
    int *m = (int*) 0x11100;
    // 直接访问野指针也会报错
    // cout << *m << endl;

    // 1.const修饰指针----常量指针
    // 常量指针:指针的指向可以更改,指针指向的值不可以更改
    float PI = 3.1415;
    float x = 0.618;
    const float* n = &PI;

    n = &x;  // 指针的指向可以更改
    // *n = 100.01; 错误

    // 2.指针常量:const修饰的是常量,指针的指向不可以更改,指针指向的值可以更改
    float y = 1.314;
    float* const ptr = &y;
    // ptr = &x; 错误,指针的指向不可以更改
    *ptr = 5.20;  // 指针指向的值可以更改


    
    // 3.const既修饰指针也修饰常量
    const int u = 520;  // 整型常量
    const int* const r = &u;
    // r = &a;  错误,指针的指向不可以更改
    // *r = 10086; 错误,指针指向的值也不可以更改



    // 创建结构体变量stu1;
    struct student stu1;

    stu1.name = "zhangsan";
    stu1.age = 18;
    stu1.score = 90;

    stu2.name = "wangwu";
    stu2.age = 15;
    stu2.score = 93;
    
    // 创建结构体变量stu3
    struct student stu3 = {"lisi", 16, 82};





    return 0;
}

你可能感兴趣的:(C++基础复习1)