0813,引用,函数重载,内存布局叭叭叭


是我4句话5个ERROR,阿巴阿巴

001_arrpointer.cc

#include <iostream>
using std::cout;
using std::endl;

void test(){
    int a[5]={1,2,3,4,5};

    int (*p)[5]=&a;
    cout<<p<<endl;
    cout<<p+1<<endl;

    int *pp=(int*)(&a+1);
    //第二个数组的首地址(*int)[5],强转成int*
    //变成第二个数组的首元素的地址
    cout<<*(a+1)<<"  "<<*(pp-1)<<endl;
}

int main(void)
{
    test();
    return 0;
}

01,引用

reference.cc

#include <iostream>
using std::cout;
using std::endl;

void test(){
    int num=100;
    int & ref=num;
    //& 不代表取值符,代表引用符号
    cout<<ref<<endl;
    ref=1000000;
    cout<<ref<<endl;

    int num2=200;
    ref=num2;//赋值

    int *p=&num;

    cout<<&num<<endl;
    cout<<&ref<<endl;//底层 cosnt poiter
    cout<<&p<<endl;
    cout<<&num2<<endl;

    /* 特殊的常量指针,无法对其进行访问,只能间接访问到指向的对象/地址 */
    cout<<endl;
    const int & ref1=num;
    /* ref1=num2; */
    /* 不希望通过引用改变其本体,const */
}

int main(void)
{
    test();
    return 0;
}

swap.cc

#include <iostream>
using std::cout;
using std::endl;

void swap(int x,int y){
}

void swap1(int *px,int *py){
    int z=*px;
    *px=*py;
    *py=z;
}

//int & a=x,int & b=y
void swap2(int & a,int &b){
    int temp=a;
    a=b;
    b=temp;
}


int num=100;
int func1(){
    return num; //执行return 语句的时候会发生copy
}
int & func2(){
//如果某个函数需要让其返回值是某个变量本身
//那么可以在函数返回类型中加上&
    return num; //no copy 
}
#if 0
int & func(){
    int num=1;
    return num;
    //num被销毁,悬空引用
    //确保引用绑定的本体的生命周期比函数更长
}
#endif
int & func4(){
    int *p=new int(10);
    return *p; //no delete
}

void test(){
    int x=6,y=90;
    swap2(x,y);
    cout<<"x="<<x<<"  y="<<y<<endl;
    swap1(&x,&y);
    cout<<"x="<<x<<"  y="<<y<<endl;

    cout<<endl;
    cout<<&num<<endl;
    cout<<func1()<<endl; //临时变量
    cout<<func2()<<endl;  //绑定到num的引用
    cout<<&func2()<<endl;//对本体进行访问

    int & ref=func4();
    cout<<ref<<endl;
    delete &ref;
    //回收
}

int main(void)
{
    test();
    return 0;
}

02,强制转换

typecast.cc           靓仔迷惑

#include <iostream>
#include <stdlib.h>
using std::cout;
using std::endl;

void test(){
    int *p=(int*)malloc(sizeof(int));
    *p=100;
    free(p);
    p=nullptr;

    int *p1=static_cast<int*>(malloc(sizeof(int)));
    *p1=100;
    free(p1);
    p1=nullptr;

    cout<<endl;
    const int num=10;
    /* int a=const_cast<int>(num); */
    /* int a=const_cast<int>(10); */

    //把能const int -->int
    const int *pp=&num;
    int *p2=const_cast<int*>(pp);
    //作用于 const引用和指向常量的指针
    *p2=100;
    cout<<*p2<<endl; //1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值