1. 程式人生 > >常量指針不能作為右值賦值給非常量指針

常量指針不能作為右值賦值給非常量指針

賦值 () using ret 一個 常量指針 err invalid 限定符

#include<iostream>
using namespace std;
int main(){
    int b[4]={1,2,3,4};
    const int* a = b;
    int * c = a;//error: invalid conversion from ‘const int*‘ to ‘int*‘ 
        return 0;
}

原因很簡單,因為常量指針是指向常量的指針,const是一個限定符,你給自己加上這個限定,不代表你可以給別人加上這個限定,因此,如果別人不是指向const的指針,你就不能強迫別人也指向const。

常量指針不能作為右值賦值給非常量指針