gpt4 book ai didi

c++ - 我可以让 C++ 编译器在编译时实例化对象吗?

转载 作者:太空狗 更新时间:2023-10-29 20:28:44 25 4
gpt4 key购买 nike

我正在编写一些代码,其中包含大量相当简单的对象,我希望它们在编译时创建。我认为编译器能够做到这一点,但我一直无法弄清楚如何做到这一点。

C 中,我可以执行以下操作:

#include <stdio.h>

typedef struct data_s {
int a;
int b;
char *c;
} info;

info list[] = {
1, 2, "a",
3, 4, "b",
};

main()
{
int i;
for (i = 0; i < sizeof(list)/sizeof(*list); i++) {
printf("%d %s\n", i, list[i].c);
}
}

使用#C++*,每个对象都调用了构造函数,而不是仅仅放在内存中。

#include <iostream>
using std::cout;
using std::endl;

class Info {
const int a;
const int b;
const char *c;
public:
Info(const int, const int, const char *);
const int get_a() { return a; };
const int get_b() { return b; };
const char *get_c() const { return c; };
};

Info::Info(const int a, const int b, const char *c) : a(a), b(b), c(c) {};

Info list[] = {
Info(1, 2, "a"),
Info(3, 4, "b"),
};

main()
{
for (int i = 0; i < sizeof(list)/sizeof(*list); i++) {
cout << i << " " << list[i].get_c() << endl;
}
}

我只是没有看到编译器无法在编译时完全实例化这些对象的信息是什么,所以我假设我遗漏了一些东西。

最佳答案

在 C++ 2011 中,您可以在编译时创建对象。为此,您需要创建各种常量表达式,但是:

  1. 需要声明构造函数constexpr
  2. 您声明的实体需要声明为constexpr

请注意,几乎所有的 const 限定符要么不相关,要么位于错误的位置。下面是一个包含各种更正的示例,并且还实际演示了 list 数组在编译期间被初始化(通过使用它的成员来定义 enum 的值):

#include <iostream>
#include <iterator>

class Info {
int a;
int b;
char const*c;

public:
constexpr Info(int, int, char const*);
constexpr int get_a() const { return a; }
constexpr int get_b() const { return b; }
constexpr char const*get_c() const { return c; }
};

constexpr Info::Info(int a, int b, char const*c)
: a(a), b(b), c(c) {}

constexpr Info list[] = {
Info(1, 2, "a"),
Info(3, 4, "b"),
};

enum {
b0 = list[0].get_b(),
b1 = list[1].get_b()
};

int main()
{
std::cout << "b0=" << b0 << " b1=" << b1 << "\n";
for (Info const* it(list), *end(list); it != end; ++it) {
std::cout << (it - list) << " " << it->get_c() << "\n";
}
}

关于c++ - 我可以让 C++ 编译器在编译时实例化对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12453623/

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