namespace glm
{
struct vec2
{
vec2(double x_, double y_):x(x_), y(y_) {}
double x;
double y;
};
}
class polygon
{
public:
polygon() {}
polygon(std::vector<glm::vec2> vec): vertices(vec) {}
std::vector<glm::vec2> vertices;
};
要在 global scope 初始化一個複雜的變數有這些方法
https://en.cppreference.com/w/cpp/language/initialization
我只講你這個例子幾個我自己會用的方法
1. Default initialization
https://en.cppreference.com/w/cpp/language/default_initialization
polygon cube_global;
cube_global.vertices的大小是0
2. List initialization
https://en.cppreference.com/w/cpp/language/list_initialization
polygon cube_global { std::vector<glm::vec2> { glm::vec2{1.0, 2.0},
glm::vec2{3.0, 4.0} } };
cube_global.vertices的大小是2
這個初始化過程是先找到polygon的建構式
polygon(std::vector<glm::vec2> { glm::vec2{1.0, 2.0},
glm::vec2{3.0, 4.0} })
然後再找到std::vector<glm::vec2>的建構式
std::vector<glm::vec2>( { glm::vec2{1.0, 2.0},
glm::vec2{3.0, 4.0} } )
最後找到glm::vec2的建構式 (註:我沒有去找glm的實作,所以先用我上面寫的定義)
glm::vec2(double x_, double y_)
3. Direct initialization
https://en.cppreference.com/w/cpp/language/direct_initialization
polygon cube_global ( std::vector<glm::vec2>( 5, glm::vec2(1.0,1.0)) );
cube_global.vertices的大小是5
這很直觀,就是呼叫什麼建構式就做什麼事
4. 使用函式進行Copy initialization(?)
https://en.cppreference.com/w/cpp/language/copy_initialization
static inline polygon polygon_factory()
{
std::vector<glm::vec2> vec2_vector;
for(int i=0;i<1250;i++)
{
vec2_vector.push_back(glm::vec2(i,i));
}
return polygon(vec2_vector);
}
polygon cube_global = polygon_factory();
cube_global.vertices的大小是1250
很特定的物件我會用這個方法