2012-09-17 39 views
3

我正在編寫一些代碼,其中包含大量合理簡單的對象,我希望它們在編譯時創建。我認爲編譯器可以做到這一點,但我一直無法弄清楚。我可以在編譯時獲得一個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; 
    } 
} 

我只是沒有看到什麼信息不可用於編譯器在編譯時完全實例化這些對象,所以我認爲我錯過了一些東西。

+0

看看靜態類或單身的idom。也許這就是你正在尋找的C++ – Najzero

+5

你得到的答案有什麼問題[程序員同樣的問題](http://programmers.stackexchange.com/questions/165008/can-i-get-ac-編譯器來實例化對象,在編譯時間)? – DCoder

+0

@Najzero C++沒有靜態類。 – juanchopanza

回答

6

在C++ 2011中,您可以在編譯時創建對象。爲此,您需要使各種常量表達式,但是:

  1. 構造函數需要聲明constexpr
  2. 您聲明的實體需要聲明constexpr

請注意,幾乎所有的const限定符都是不相關的或位置錯誤。下面是與各種校正的示例,並且實際上也證明(通過使用它的部件以限定enum的值),該list陣列在編譯時期間初始化:

#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"; 
    } 
} 
+0

對於'constexpr get_a','a'和'b'不需要是'const'合法嗎?或者'constexpr'對象是可修改的(我知道它們是私有的,但是如果我對'Info'對象上的'a'賦值,會發​​生什麼? – ted

+0

@ted:成員不需要是'constexpr',因爲整個對象是'constexpr'。如果你想從非'const'對象中獲得'constexpr',但是訪問一個成員需要成爲'constexpr'的成員(當然,還有定義這個成員的其他東西) –

+0

謝謝你的解釋,你的意思是* by *你在哪裏寫*但是*? – ted

相關問題