2013-02-20 29 views
3

我想在C++中定義一個具有屬性的結構來返回它自己類型的預定義值。返回一個自己類型的結構的Struct屬性

像很多的API有載體和顏色,如:

Vector.Zero; // Returns a vector with values 0, 0, 0 
Color.White; // Returns a Color with values 1, 1, 1, 1 (on scale from 0 to 1) 
Vector.Up; // Returns a vector with values 0, 1 , 0 (Y up) 

來源:http://msdn.microsoft.com/en-us/library/system.drawing.color.aspx (MSDN的頁面的顏色類型的)

我一直在試圖尋找了幾個小時,但我可以」對我來說,我甚至可以弄清楚它叫做什麼。

回答

2

你可以用靜態成員模仿它:

struct Color { 
    float r, g, b; 
    Foo(float v_r, float v_g, float v_b): 
     r(v_r), g(v_g), b(v_b){}; 
    static const Color White; 
}; 

const Color Color::White(1.0f, 1.0f, 1.0f); 

// In your own code 
Color theColor = Color::White; 
2

這是一個靜態屬性。不幸的是,C++沒有任何類型的屬性。要實現這個,你可能需要一個靜態方法或一個靜態變量。我會推薦前者。

對於Vector例如,你想是這樣的:

struct Vector { 
    int _x; 
    int _y; 
    int _z; 

    Vector(int x, int y, int z) { 
    _x = x; 
    _y = y; 
    _z = z; 
    } 

    static Vector Zero() { 
    return Vector(0,0,0); 
    } 
} 

這樣,你會寫Vector::Zero()得到零向量。

4
//in h file 
struct Vector { 
int x,y,z; 

static const Vector Zero; 
}; 

// in cpp file 
const Vector Vector::Zero = {0,0,0}; 

是否這樣?