如何将“指针转换为指针类型”到const? [英] How to convert "pointer to pointer type" to const?

查看:499
本文介绍了如何将“指针转换为指针类型”到const?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下代码

  void TestF(const double ** testv){;} 
void callTest ){
double ** test;
TestF(test);
}

我得到:

 'TestF':无法将参数1从'double **'转换为'const double **'

我不明白为什么。
为什么 test 不能被默认转换为 const double **
我为什么要明确地做它?我知道

  TestF(const_cast< const double **>(test))



使我的代码正确,但我认为这是不必要的。



关于 const 的一些关键概念,我错过了?

解决方案

语言允许从 double ** 隐式转换为 const double * const * ,但不能 const double **



[de-facto standard] C ++常见问题解答中的示例说明了如何使用const正确性的规则,



http:/ /www.parashift.com/c++-faq/constptrptr-conversion.html



基本上,规则是:一旦您添加 const 在某种级别的间接,你必须添加 const 到所有级别的间接一直到右边。例如, int ***** 不能隐式转换为 int ** const *** ,但它可以隐式转换为 int ** const * const * const *


With the following code

void TestF(const double ** testv){;}
void callTest(){
    double** test;
    TestF(test);
}

I get this:

'TestF' : cannot convert parameter 1 from 'double **' to 'const double **'

I cannot understand why. Why test cannot be silently casted to const double**? Why should I do it explicitly? I know that

TestF(const_cast<const double**>(test)) 

makes my code correct, but I feel this should be unnecessary.

Are there some key concepts about const that I'm missing?

解决方案

The language allows implicit conversion from double ** to const double *const *, but not to const double **. The conversion you attempt would implicitly violate the rules of const correctness, even though it is not immediately obvious.

The example in the [de-facto standard] C++ FAQ illustrates the issue

http://www.parashift.com/c++-faq/constptrptr-conversion.html

Basically, the rule is: once you add const at some level of indirection, you have to add const to all levels of indirection all the way to the right. For example, int ***** cannot be implicitly converted to int **const ***, but it can be implicitly converted to int **const *const *const *

这篇关于如何将“指针转换为指针类型”到const?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆