• 引用


    void test(int & val);
    void test2(const int & val);
    void test3(int val);
    struct Person{
        string name;
        int age;
        int weight;
    };
    
    
    
    int main() {
        int rats = 10;
        int & rodents = rats; //必须在创建的时候进行初始化
    
        //创建引用的地址指向源值,地址相同
        int *p = &rats;
        cout << rats << "address : " << &rats <<endl;
        cout << rodents << "address : " << &rodents <<endl;
        cout << *p << "address : " << p << endl;
        //通过引用的方式,将会修改 实参的值 可以通过 const进行修饰防止修改
        //如果函数调用的参数不是左值 const引用参数类型不匹配,c++将创建匿名临时变量
        //函数调用参数的值将传递给这个匿名变量,并让参数引用该变量
      // 普通参数传递则是对参数的临时复制,相对指针和引用效率要低很多
    double b = 1.0; //test2(rats); test2(b); test3(b);
      
    const Person & clone(const Person & p){
    //参数为引用 const修饰 则不能直接通过指针引用需要加const修饰
    const Person *tmp;
    tmp = &p;
    return *tmp;
    }
    
    
    
    return 0;
    }
    void test(int & val){ val *= val; } void test2(const int & val){ val *= val; //编译不通过 只有只读权限 cout << val << endl; } void test3(int val){ cout << val << endl; }
  • 相关阅读:
    用VS Code写C++程序如何运行
    DRF
    DRF
    DRF
    DRF
    DRF
    DRF
    DRF
    DRF
    DRF
  • 原文地址:https://www.cnblogs.com/alplf123/p/8026244.html
Copyright © 2020-2023  润新知