C++ 常数的无效加法?错误:无法使用char**初始化常量char**
Solaris Studio正在生成最令人费解的错误消息C++ 常数的无效加法?错误:无法使用char**初始化常量char**,c++,solaris,solaris-studio,C++,Solaris,Solaris Studio,Solaris Studio正在生成最令人费解的错误消息 158 char* inbufptr = buffer; 159 char* outbufptr = outbuf; 160 161 const char** inbufptrpos = &inbufptr; 错误消息是: 第161行:错误:无法使用字符**初始化常量字符** 为什么添加常量会有问题?我被困住了,请帮帮我 指针char*inbufftr指向数组的开头,并不保证保持任何常量 现在,如果我现在有一个指针char
158 char* inbufptr = buffer;
159 char* outbufptr = outbuf;
160
161 const char** inbufptrpos = &inbufptr;
错误消息是:
第161行:错误:无法使用字符**初始化常量字符**
为什么添加常量会有问题?我被困住了,请帮帮我
指针char*inbufftr指向数组的开头,并不保证保持任何常量 现在,如果我现在有一个指针char const**inBufftr_pos,那么这种类型保证不会更改数组的内容,但我仍然可以更改指针指向的位置。如果我这样做了,我就没有更改阵列,我看不出有什么问题。假设这是合法的
char* inbufptr = buffer;
const char** inpufptrpos = &inbufptr;
现在您可以更改inbufptr
,但是inpufptrpos
是const
,因此不应该更改它。你看这没什么意义。这就像const
不受尊重一样
在答案的帮助下,我希望这有帮助!:) 这是一个由来已久的问题,直觉上你认为你可以“添加
const
ness”,但实际上添加const
ness间接地违反了const
-正确性
标准本身甚至有一个例子可以帮助人们回到正确的道路上:
#include <cassert>
int main() {
char* p = 0;
//char const** a = &p; // not allowed, but let's pretend it is
char const** a = (char const**)&p; // instead force the cast to compile
char const* orig = "original";
*a = orig; // type of *a is char const*, which is the type of orig, this is allowed
assert(p == orig); // oops! char* points to a char const*
}
#包括
int main(){
char*p=0;
//char const**a=&p;//不允许,但让我们假设它是
char-const**a=(char-const**)&p;//而是强制编译强制转换
char const*orig=“原件”;
*a=orig;//类型*a是char const*,这是orig的类型,这是允许的
assert(p==orig);//oops!char*指向一个char常量*
}
inpufptrpos
不是问题所在(例如,你可以有intx=5;const int*ptr=&x;x=6;
并且没有问题——这与你的例子相当)是的,我没有想到,谢谢,顺便问一个好问题@初学者,+1!
#include <cassert>
int main() {
char* p = 0;
//char const** a = &p; // not allowed, but let's pretend it is
char const** a = (char const**)&p; // instead force the cast to compile
char const* orig = "original";
*a = orig; // type of *a is char const*, which is the type of orig, this is allowed
assert(p == orig); // oops! char* points to a char const*
}