注册 登录
编程论坛 C++教室

const问题

humy 发布于 2012-08-09 10:14, 811 次点击
书上一段:
const int ci=0;
const int *p=&ci;//convert address of non-const to address of a const
后面注释的address of non-const对吗?ci不是const吗?
15 回复
#2
修雅2012-08-09 16:30
const int ci=0;//ci的值是const 但是 &ci不是 就是ci的地址是可以变的
const int *p=&ci//这里*p是const 就是指向&ci的地址
当然 如果以后ci的地址变了,*p所指的地址是不会跟&ci变的
#3
pangding2012-08-09 23:37
感觉没什么问题呀。你后面的那个注释是编译器的警告吗?
#4
humy2012-08-11 08:20
回复 3楼 pangding
不是。是书上的
#5
humy2012-08-11 08:21
回复 2楼 修雅
const int*说明是指向const int的指针,而原来ci不就是吗
#6
pangding2012-08-11 11:13
可能是书上想说非常量的也能这么用吧。
程序代码:
const int ci = 1;
int i = 2;
const int *p;
p = &ci; // OK
p = &i;  // OK
*p = 3;  // error
i = 3;   // OK

反正搞清楚相关的语法就行了,书上说的东西也不一定都是对的。
#7
lxqlyld2012-08-11 20:41
没有错误啊,你用的是什么编译软件啊,我用的是C++ Builder 6.0 编译通过
#8
lz10919149992012-08-11 21:15
很明显是注释有问题啦,作者一时疏忽。
#9
水古奇影2012-08-11 21:52
楼上说的对,注释有错误,*p和ci是const, p和&ci不是const
#10
humy2012-08-11 22:38
谢谢大家了。。。
#11
hamsters2012-08-12 20:54
const int ci = 1;
int i = 2;
const int *p;
p = &ci; // OK
p = &i;  // OK
*p = 3;  // error
i = 3;   // OK


反正搞清楚相关的语法就行了,书上说的东西也不一定都是对的。
我用编译器试了一下,还真是这样
#12
有容就大2012-08-13 07:42
const int *p=&ci;//convert address of non-const to address of a const
把一个可变地址(&ci) 转到不可变地址下(*p) 注释应该是想说这个吧
#13
humy2012-08-14 18:52
有师兄回答我说:
注意&cj所指向的内容,0,其本身类型为int而非const int,亦即,此时&ci所指对象确
实为non-const,且&ci本身为非const限定指针。
至于为何在const int ci =0这句中完成类型转换,多半是因为内置类型赋值采取的是值
传递方式。
int i;
: const int ci = 0;
: const int &j = i;   // ok: convert non-const to reference to const int
: const int *p = &ci; // ok: convert address of non-const to address of a const
那我想问0不是常数吗?怎么只是int不是const int?即使不是,他赋值给const int时就强制转化了吧?
#14
pangding2012-08-14 22:37
const int ci = 0; 应该理解成常变量的初始化:0 为整形字面,语义上是 int。这里一般不用类型转换这上提法,是只用 0 这个值来初始化 const int 这个常变量。

另外对 const int 取地址,返回的表达式应该是 coonst int * 的类型。你说由于值是 0,因而是 int * 是不对的。
静态类型语言的类型的确定,是看对象的类型,而不是看它的值。
#15
humy2012-08-15 08:21
回复 14楼 pangding
谢谢,就是说,还是书上那个注释错了,对吧
#16
pangding2012-08-15 10:23
个人感觉是。不过这种地方也不用太较真。
1