C语言 与 C++ 对这个语法的兼容程度不同
C++ 需要转换类型:
[root@3b5a7bbbd55f hello_const]# clang++ hello_const_.cpp
hello_const_.cpp:47:9: error: no matching function for call to 'print_const_one'
print_const_one(3, data_ptr);
^~~~~~~~~~~~~~~
hello_const_.cpp:15:6: note: candidate function not viable: no known conversion from 'float **' to 'const float **' for 2nd argument
void print_const_one(int len, const float* data_ptr[]){
^
1 error generated.
[root@3b5a7bbbd55f hello_const]#
[root@3b5a7bbbd55f hello_const]# g++ hello_const_.cpp
hello_const_.cpp: In function 'int main()':
hello_const_.cpp:47:36: error: invalid conversion from 'float**' to 'const float**' [-fpermissive]
print_const_one(3, data_ptr);
^
hello_const_.cpp:15:6: note: initializing argument 2 of 'void print_const_one(int, const float**)'
void print_const_one(int len, const float* data_ptr[]){
^~~~~~~~~~~~~~~
[root@3b5a7bbbd55f hello_const]#
C语言自动转换:
[root@3b5a7bbbd55f hello_const]# gcc hello_const_.c
hello_const_.c: In function 'main':
hello_const_.c:47:28: warning: passing argument 2 of 'print_const_one' from incompatible pointer type [-Wincompatible-pointer-types]
print_const_one(3, data_ptr);
^~~~~~~~
hello_const_.c:15:6: note: expected 'const float **' but argument is of type 'float **'
void print_const_one(int len, const float* data_ptr[]){
^~~~~~~~~~~~~~~
[root@3b5a7bbbd55f hello_const]#
[root@3b5a7bbbd55f hello_const]# clang hello_const_.c
hello_const_.c:47:28: warning: passing 'float **' to parameter of type 'const float **' discards qualifiers in nested pointer types [-Wincompatible-pointer-types-discards-qualifiers]
print_const_one(3, data_ptr);
^~~~~~~~
hello_const_.c:15:44: note: passing argument to parameter 'data_ptr' here
void print_const_one(int len, const float* data_ptr[]){
^
1 warning generated.
[root@3b5a7bbbd55f hello_const]# ls
a.out hello_const_.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void print_const_one____(int len, const float* data_ptr[]){
printf("2__\n");
const float* b=data_ptr[1];
for(int i=0; i<len; i++){
printf("b[%d]=%f ", i, b[i]);
}
}
void print_const_one(int len, const float* data_ptr[]){
printf("1__\n");
const float* a=data_ptr[0];
for(int i=0; i<len; i++){
printf("a[%d]=%f ", i, a[i]);
}
printf("\n");
print_const_one____(3, data_ptr);
printf("\n");
}
int main(){
float a[3] = {1.1, 2.2, 3.3};
float b[3] = {4.4, 5.5, 6.6};
float* a_ = (float*) malloc(3*sizeof(float));
float* b_ = (float*) malloc(3*sizeof(float));
memcpy(a_, a, 3*sizeof(a[0]));
memcpy(b_, b, 3*sizeof(b[0]));
float** data_ptr = (float**)malloc(2*sizeof(float*));
data_ptr[0] = a_;
data_ptr[1] = b_;
// print_const_one(3, data_ptr);// gcc
print_const_one(3, const_cast<const float**>(data_ptr));// g++
return 0;
}