您的位置:首页 > 编程语言 > C语言/C++

C++ const总结

2016-06-16 09:05 337 查看
先说结论

非引用类型的赋值无所谓const。

const引用可以指向const及非const。但非const引用只能指向非const。

指向const的指针,可以指向非const。但指向非const的指针,只能指向非const。

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

   对于函数来说同理

    非const引用的形参只能接收非const引用的实参;const引用的形参可以接收任意引用的实参。

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

    对引用来说,const形参和非const形参,函数是不同的!!!指针没这区别。

插一句

指针和引用,非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 [b]relaxed[/b] in C++11, with the addition of rvalue references


代码说明一切

#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: