gpt4 book ai didi

c++ - constexpr 用指针初始化

转载 作者:可可西里 更新时间:2023-11-01 15:53:42 27 4
gpt4 key购买 nike

我正在尝试使用指向 int 的指针来初始化 constexpr 声明,int 是一个 const 对象。我也尝试用一个不是 const 类型的对象来定义一个对象。

代码:

#include <iostream>

int main()
{
constexpr int *np = nullptr; // np is a constant to int that points to null;
int j = 0;
constexpr int i = 42; // type of i is const int
constexpr const int *p = &i; // p is a constant pointer to the const int i;
constexpr int *p1 = &j; // p1 is a constant pointer to the int j;
}

g++ 日志:

constexpr.cc:8:27: error: ‘& i’ is not a constant expression
constexpr.cc:9:22: error: ‘& j’ is not a constant expression

我相信这是因为 main 中的对象没有固定地址,因此 g++ 向我返回错误消息;我将如何纠正这个?不使用文字类型。

最佳答案

让它们静态来修复它们的地址:

int main()
{
constexpr int *np = nullptr; // np is a constant to int that points to null;
static int j = 0;
static constexpr int i = 42; // type of i is const int
constexpr const int *p = &i; // p is a constant pointer to the const int i;
constexpr int *p1 = &j; // p1 is a constant pointer to the int j;
}

这称为地址常量表达式 [5.19p3]:

An address constant expression is a prvalue core constant expression of pointer type that evaluates to the address of an object with static storage duration, to the address of a function, or to a null pointer value, or a prvalue core constant expression of type std::nullptr_t.

关于c++ - constexpr 用指针初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13499658/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com