C++ const总结

先说结论ios

  • 非引用类型的赋值无所谓const。
  • const引用能够指向const及非const。但非const引用只能指向非const。
  • 指向const的指针,能够指向非const。但指向非const的指针,只能指向非const。

注意:上面说的都是变量赋值!express

     对于函数来讲同理函数

    非const引用的形参只能接收非const引用的实参;const引用的形参能够接收任意引用的实参。测试

    非const指针的形参只能接收非const指针的实参;const指针的形参能够接收任意指针的实参。this

    对引用来讲,const形参和非const形参,函数是不一样的!!!指针没这区别。spa

 

插一句指针

指针和引用,非const的不能指向const吧,为何char *cc="abbc"就能够?
网上说“是字面值常量的指针其实指向临时对象,C++规定指向临时对象的指针必须const”。
那这里C++是怎么处理的? 
  
this is not good wording...  
it starts from "temporary objects can be bound to const references and have their lifetimes extended to that of the bound reference",
and you can only get a pointer-to-const from such a ref but this is constraint is relaxed in C++11, with the addition of rvalue references

 

代码说明一切code

#include <iostream>
#include <string>

using namespace std;

//test const
int main(){
    //------------测试非引用------------
    int no=10;
    const int no2=no; //OK
    int no3=no2; //OK!
    //上面得出结论:非引用类型的赋值无所谓const //------------测试引用------------ 
    int &noref=no;
    const int &noref1=no;

//    int &no2ref=no2;
    const int &no2ref1=no2;

    int &no3ref=no3; 
    const int &no3ref1=no3;
    // 上面得出结论:const引用能够指向const及非const。但非const引用只能指向非const。 //------------测试指针------------
    int *pno=&no;
    const int *pno_1=&no;//指向const的指针,能够指向非const 

//    int *pno2=&no2;//指向非const的指针,只能指向非const 
    const int *pno2_1=&no2;

    int *pno3=&no3;
    const int *pno3_1=&no3;
    // 上面得出结论:见备注    


    return 0;
}

 

函数测试代码对象

#include <iostream>

using namespace std;

void print(int&);
void print2(const int& val);
void getx(char *c);
void getx2(const char *c);
int main(){
    
    int v1=2;
    const int v2=10;
    print(v1);
//    print(v2);//[Error] invalid initialization of reference of type 'int&' from expression of type 'const int'
    
    print2(v1);
    print2(v2);
    
    int& v3=v1;
    const int& v4=v2;
    
    print(v3);
//    print(v4);////[Error] invalid initialization of reference of type 'int&' from expression of type 'const int'
    
    print2(v3);
    print2(v4);
    
    //总结,非const的引用类型的形参,只能接收同类型的实参!
    
    // ------------------------
    char *c1="abc";
    const char *c2="xyz"; 
    getx(c1);
//    getx(c2);//[Error] invalid conversion from 'const char*' to 'char*' [-fpermissive]
    
    getx2(c1);
    getx2(c2);
    
    return 0;
}

void print(int& val){
    cout << val << endl;
} 

void print2(const int& val){
    cout<<val<<endl;
} 


void getx(char *c){
    cout<<c<<endl;
}
void getx2(const char *c){
    cout<<c<<endl;
}
相关文章
相关标签/搜索