源:http://www.cppblog.com/izualzhy/archive/2011/10/12/158170.aspx
{
*p2 = 2;
}
int main()
{
int a = 1;
const int *p = &a;
f(p);
}
准备工作完毕!
一直以为const char*实参传给char *形参是不对的,不过写c程序时竟编译过了?!运行结果也正确,百思不得其解。。。http://www.cppblog.com/izualzhy/archive/2011/06/12/148553.html
c源程序:
zhy@desktop:~/doublemint/factory$ gcc testConst.c
testConst.c: In function ‘main’:
testConst.c:9: warning: passing argument 1 of ‘f’ discards qualifiers from pointer target type
后缀名改成cpp后,编译不通过!:
zhy@desktop:~/doublemint/factory$ gcc testConst.cpp
testConst.cpp: In function ‘int main()’:
testConst.cpp:9: error: invalid conversion from ‘const int*’ to ‘int*’
testConst.cpp:9: error: initializing argument 1 of ‘void f(int*)’
先查了下gcc的使用:
(1)后缀为.c的,gcc把它当作是C程序,而g++当作是c++程序;后缀为.cpp的,两者都会认为是C++程序,注意,虽然C++是C的超集,但是两者对语法的要求是有区别的。C++的语法规则更加严谨一些。
(2)编译阶段,g++会调用gcc,对于C++代码,两者是等价的,但是因为gcc命令不能自动和C++程序使用的库联接,所以通常用g++来完成链接,为了统一起见,干脆编译/链接统统用g++了,这就给人一种错觉,好像cpp程序只能用g++似的。
推测答案应该是因为c++语法规则更严谨导致的。
http://zhidao.baidu.com/question/328492252.html
类似于
class Test {
};
const Test t;
Test &t2 = t;//error: invalid initialization of reference of type "X&"
//from experssion of type "const X"
即相当于const指针或者引用赋给普通指针或者引用,是不对的。
由此引出之前的一个不明白的地方,就是
const Test f();这种函数定义了const返回的意义?
我们使用引用来接收(返回普通值是复制,对这种接收方法,定义const返回确实没有意义)
const Test &t3 = f();因此t3是有const属性的。
而Test &t4 = f();接受则会提示上面提到的错误。
不过这只是语法上使const Test f()与Test f()的使用不同而已。
因为这么定义肯定是要使用返回值的复制体,感觉使用上也没有什么区别呢。。。。
这个问题还是未解决,以后看代码多留意下这种函数定义出现的地方。
同时也去翻了下百度知道里那位仁兄提到的c++primer的部分:
的确提到了这么一句:
提示:如果把指向const的指针理解为“自以为指向const的指针”,这可能会对理解有所帮助。
用了以下代码作为例子:
double dval = 3.14;
const double *cptr = &dval;
dval = 3.1415926; //dval is not const,*cptr changed
*cptr = 3.1415926; //error: cptr is a pointer to const