C++ 非 const 到 const 转换编译错误

标签 c++ casting const-cast

下面的代码无法编译

void aaa(const int **a) {
}

int *a[] = {new int[2]};
aaa(a);

我在 VS2010 中遇到“无法将参数 1 从‘int [1]’转换为‘const int *”,在 gcc 中遇到类似错误

当我将声明更改为:

int const *a[] = {new int[2]};

const int *a[] = {new int[2]};

它可以编译,但我不明白为什么它不接受非 const 变量声明

最佳答案

a的类型是int*[];您想要的类型是 int const**int*[] 转换为 int**,但这不会隐式转换为 整数常量**。考虑以下代码以了解原因:

static int const ci = 42;

void aaa( int const** out )
{
    *out = &ci;
}

int
main()
{
    int* pa;
    aaa( &pa );     //  NOT LEGAL, because...
    *pa = 0;        //  would now change ci
    std::cout << ci << std::endl;
    return 0;
}

如您所见,允许此转换会破坏常量 需要类型转换。

根据你在做什么,你可能想使用:

void aaa( int const* const* out );

int**int const *const * 的隐式转换是合法的。 (否则,您需要在某处使用 const_cast 来告诉编译器 你知道自己在做什么,这不是真正的问题。)

关于C++ 非 const 到 const 转换编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9428044/

相关文章:

c++ - 如何初始化常量 int 以用于数组大小?

c++ - 强制外部函数为 const

python - 在python中读取时将文本的所有值转换为int

sql - 在postgresql 9.1.3中执行类型转换功能与在postgresql 8.2.22中不同。串联无法正常工作

java - 将 Set<Object> 转换为 Collection<String>

c++ - 定期使用 const_cast 作为设计工具是否可以接受?

c++ - const_cast<double*> 有效但 const_cast<int*> 无效

c++ - 关于使用 C++ 使用命令行参数调用 CreateProcessAsUser 的说明

c++ - Qt c++ 应用程序抓取

c++ - 将 unique_ptr<Derived<T>> 传递给函数