3

我正在尝试在 C++ 中定义一个结构,该结构具有返回其自身类型的预定义值的属性。

就像许多用于矢量和颜色的 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 的颜色类型页面)

我一直在努力寻找几个小时,但我的内心甚至无法弄清楚它叫什么。

4

3 回答 3

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

 static const Vector Zero; 
};

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

像这样?

于 2013-02-20T05:17:09.843 回答
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()得到零向量。

于 2013-02-20T05:15:07.453 回答
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;
于 2013-02-20T05:31:31.377 回答