[C ++ 11] CONSTとポインタと参照

参照が存在し、参照は、参照音符の添加はちょうど参照ではなく、値渡しされるので、最初に削除して、ポインタのconstを分析することができます

#include <iostream>
#include <string>

using namespace  std;
void function1(int const* const& t)
//t是一个常量引用,说明绑定的值不能改变  //引用传递
//是一个指针的引用(别名) 指向一个int类型的常量
{
    //*t = 4;//指向的内容不能变
    cout << t << endl;//地址
    cout << *t << endl;

    const int s = 3;
    //t = &s;//error 指向也不能改变
}

void function2(int *const& t)
//引用传递
//int * const t;//t是一个常量指针 说明指向不能变 指向一个int类型的变量 说明指向的内容可以变
{
    *t = 4;
    cout << t << endl;
    cout << *t << endl;
}
void function3(int* & t)
//引用传递
//int * t;//t是一个指针,说明指向可以变 指向的是int类型的变量 说明指向的内容也可以变
{
    int j = 4;
    t = &j;
    cout << t << endl;
    cout << *t << endl;

    int s = 0;
    t = &s;
    cout << t << endl;
    cout << *t << endl;
}

int main()
{
    const int i = 10;
    function1(&i);
    int j = 10;
    function2(&j);//function2(&i);//error 说明function2需要的是一个不是const的地址
    int* p;
    function3(p);//function3(&i);function3(&j);//error 不需要一个地址-->常量 而是需要一个变量


    return 0;
}

おすすめ

転載: www.cnblogs.com/tailiang/p/11727399.html