关于C++的常量的一个问题

来源:百度知道 编辑:UC知道 时间:2024/05/12 16:07:31
void aa( const int*ip,void(*bb)() ){
cout<<*ip<<endl:
(*bb)();
cout<<*ip<<endl;
}

int i=5;
void cc{
++i;
}
为啥执行上述代码时会更改ip所指?
希望各位高手解释清楚,不求快,只求准
漏了个主函数main(){
aa(&i,cc)
}

ip指向i的
所以 i 变化了,*ip 就会变
const int*ip 只是保证 在本函数中不能改变 *ip的值,
也就是 (*ip )++会错
但不能保证i在外面被修改

我来改一下你的代码吧,因为你的代码写得不完整:
#include <iostream.h>
{
main()
using namespace std;
void aa( const int*ip,void(*bb)() ){
cout<<*ip<<endl;
(*bb)();
cout<<*ip<<endl;
}

int i=5;
void cc(){
++i;
}

void main()
aa(&i,cc) ;
}
我想是你的花括号弄错了,因为每一个花括号所括在里面的函数一般都是要运行的,你复制一下上面的代码去运行一下,看行不行,因为这是在网吧!没有帮你运行,你试一下吧!

2楼和6楼正解。

c++ 常量指针中存在3:
1:指向常量的指针 :const int*ip ip所指向的地址不可变,但存储的变量值可变
2:常指针:int const *ip ip所指向的地址可变, 但存储的变量值不可变

3:指向常量的常指针 const int const *ip 两者均不改变

const int * ip 指 ip是const指针
int const * ip 指 ip指向是const int 类型

在 The C++ Primer里有解释

const int * ip 指 ip是const指针

所以,再运行cc()回报错