我正在編寫一些代碼,其中包含大量合理簡單的對象,我希望它們在編譯時創建。我認爲編譯器可以做到這一點,但我一直無法弄清楚。我可以在編譯時獲得一個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;
}
}
我只是沒有看到什麼信息不可用於編譯器在編譯時完全實例化這些對象,所以我認爲我錯過了一些東西。
看看靜態類或單身的idom。也許這就是你正在尋找的C++ – Najzero
你得到的答案有什麼問題[程序員同樣的問題](http://programmers.stackexchange.com/questions/165008/can-i-get-ac-編譯器來實例化對象,在編譯時間)? – DCoder
@Najzero C++沒有靜態類。 – juanchopanza