【问题标题】:"int" and "const int" initialization and conversion in C++C++中的“int”和“const int”初始化和转换
【发布时间】:2013-08-04 22:16:04
【问题描述】:

我在我的程序中编写了以下代码行:

const int *dims = {4};

但它向我报告了以下错误:

“int类型的值不能用于初始化const int类型的实体”

谁能告诉我发生了什么并教我一个解决方法?(条件dims的数组仍然是const

【问题讨论】:

  • 好吧,就像它说的你不能用4初始化const int*。你为什么这样做?
  • 因为我想使用另一个人编写的函数,它接受参数 const int *dims。而且我想使用 int 一种安全的方式,这样我就可以避免自动类型转换等
  • 不知道这是否可以被视为正确的选择或这样做的安全选择:int dims1 = {4};const int *dims = &dims1;
  • 对于矩阵使用双指针
  • 错误信息中没有*吗?

标签: c++ pointers initialization constants


【解决方案1】:

代码const int *dims = {4}; 表示将指针dims 赋值为4。 但是为什么你想要一个指向内存位置 4 的指针呢?这不太可能是你想要的,不允许这样做。

以下是获取指向值为 4 的 const int 的指针的一些选项:

const int *dims = new int(4);  // beware someone needs to delete dims

对于自动生命周期,如在堆栈中:

const int autoDims(4);     // Will be deleted when autoDims goes out of scope
const int *dims(&autoDims);

或:

const int dims[] = {4};    // Will be deleted when dims goes out of scope

如果你真的想要一个值为 4 的指针,你必须显式地转换为指针类型:

const int *dims = (int *)4;

【讨论】:

    【解决方案2】:

    编译器抱怨是因为你试图用一个整数初始化一个指针。

    您所指的函数可能期望传递一个数组。您可以使用常量数组调用它,如下所示:

    const int dim[4] = {1,2,3,4};
    
    foo(dim);
    

    【讨论】:

      猜你喜欢
      • 2021-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-30
      • 2021-06-21
      • 1970-01-01
      • 1970-01-01
      • 2016-08-14
      相关资源
      最近更新 更多