【问题标题】:initialise const struct with const pointer用 const 指针初始化 const 结构
【发布时间】:2016-02-18 23:28:38
【问题描述】:

我想从传递给函数的 const 参数形成一个结构。由于参数是常量,我猜结构也必须是常量。但是,它不适用于指针。

以下代码编译(MinGW 4.9.2 32bit)

struct structType_t {
    int b;
};

void func1(const int b) {
    const structType_t s={b};  // invalid conversion from 'const int*' to 'int*' [-fpermissive]

    // do something with s;
}

但有了指针就不行:

struct structType_t {
    int* b;
};

void func1(const int* b) {
    const structType_t s={b};  // invalid conversion from 'const int*' to 'int*' [-fpermissive]

    // do something with s;
}

为什么编译器要在这里抛弃 const? 那么如何使用 const 指针来初始化 const 结构呢?

【问题讨论】:

  • structType 有 int* b 而不是 const int* b
  • const intint const是同一种类型,const int*int* const是不同的类型。
  • 即使我将 b 的类型更改为 const int * const 它也不会编译。我找到的唯一解决方案是 const_cast,我想这里是完全安全的。但我想知道,为什么我需要带有指针的 const_cast 而不是整数。

标签: c++ pointers struct constants


【解决方案1】:

如果您将结构更改为保存const int*,则可以使用它来存储传递给函数的const int*,无论您的s 是否为const

struct structType_t {
    const int* b;
};

void func1(const int* b) {
     const structType_t s={b};
     // or 
     structType_t s2={b};

    // do something with s or s2 ...
}

【讨论】:

  • 我不能改变结构来保存一个常量。但是,将结构声明为 const 会使所有成员都变为 const,对吗?
  • 是的,它将使它持有一个指向 int (int* const) 的 const 指针,但不是指向 const int (const int*) 的指针,这是您要存储的内容。跨度>
【解决方案2】:

在第一种情况下,您正在创建一个 int 的副本。 const int 的副本不必是 const 所以它可以工作。 在第二种情况下,您正在创建指向 const int 的指针的副本并将其分配给指向 int 的指针 - 这是不允许的,这就是它无法编译的原因。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-08
    • 2022-11-23
    • 2014-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多