你能在使用typedef时重命名成员吗

Can you rename members when using typedef?

本文关键字:重命名 成员 typedef      更新时间:2023-10-16

我使用一个由三个float组成的结构来表示平移和缩放,如下所示:

typedef struct Translation{
    Translation() : x(0.0), y(0.0), z(0.0){};
    Translation(x, y, z) : x(x), y(y), z(z){};
    //some arithmetic operators
    float x, y, z;
}
Translation;
typedef Translation Scale;

现在我也想用这个定义来表示Rotation,但我不想访问它们的成员xyz,而是访问yawpitchroll。有可能通过typedef对成员进行这样的重命名吗?或者还有其他方法不包括重新定义完整的结构及其成员?

否,因为typedef用于类型(例如int、double等)。

最清楚的方法是制作另一个结构。

编辑:由于这是C++,我建议您创建一个基类,该基类包含所有逻辑并从中派生。换句话说,使用继承

示例:

#include <iostream>
class Base {
 public:
  Base(int aa, int bb, int cc)
   : a(aa), b(bb),c(cc) {}
  int getA() {
    return a;
  }
  int getB() {
    return b;
  }
  int getC() {
    return c;
  }
  // Notice that you make the data members private,
  // but then you will need the getters to access them
  // in the derived classes
 protected:
  int a;
  int b;
  int c;
};
class A : public Base {
 public:
  A(int aa, int bb, int cc)
   : Base(aa, bb, cc) {}
  int x() {
    return a;
  }
  int y() {
    return b;
  }
  int z() {
    return c;
  }
};
class B : public Base {
 public:
  B(int aa, int bb, int cc)
   : Base(aa, bb, cc) {}
  int gama() {
    return a;
  }
  int beta() {
    return b;
  }
  int theta() {
    return c;
  }
};
int main() {
  A a_object(1, 2, 3);
  B b_object(4, 5, 6);
  std::cout << "a of a_object = " << a_object.x() << "n";
  std::cout << "b of b_object = " << b_object.gama() << "n";
  return 0;
}

因此,我的观点如下:它可能并不完美,但允许同时轻松修改所有三个struct,同时保留所有三种类型的清晰分离,正如@Oktalist所指出的,这一点非常重要。这三种类型之间不应该存在互操作性,因此继承和typedef不是一个选项。

所以,我在Macros:中找到了解脱

#define THREE_FLOAT_STRUCT(NAME, X, Y, Z, X_STANDARD, Y_STANDARD, Z_STANDARD) typedef struct NAME{
    NAME() : X(X_STANDARD), Y(Y_STANDARD), Z(Z_STANDARD){};
    NAME(float X, float Y, float Z) : X(X), Y(Y), Z(Z){};
    NAME operator+(const NAME& other) const{ return NAME(X + other.X, Y + other.Y, Z + other.Z); }
    NAME operator-(const NAME& other) const{ return NAME(X - other.X, Y - other.Y, Z - other.Z); }
    NAME operator*(float divisor) const{ return NAME(X * divisor, Y * divisor, Z * divisor); }
    NAME operator/(float divisor) const{ return NAME(X / divisor, Y / divisor, Z / divisor); }
    NAME& operator+=(const NAME& other){ X += other.X; Y += other.Y; Z += other.Z; return *this; }
    NAME& operator-=(const NAME& other){ X -= other.X; Y -= other.Y; Z -= other.Z; return *this; }
    NAME& operator*=(float divisor){ X *= divisor; Y *= divisor; Z *= divisor; return *this; }
    NAME& operator/=(float factor){ X /= factor; Y /= factor; Z /= factor; return *this; }
    float X, Y, Z;
} NAME;
THREE_FLOAT_STRUCT(Rotation, roll, pitch, yaw, 0.0, 0.0, 0.0)
THREE_FLOAT_STRUCT(Translation, x, y, z, 0.0, 0.0, 0.0)
THREE_FLOAT_STRUCT(Scale, x, y, z, 1.0, 1.0, 1.0)

我个人喜欢这种解决方案。它确实有点难读,但我们只谈论基本的算术运算,代码没有太花哨的地方,你可以一眼就能看到定义了哪些运算符。

如果你有更好的解决方案,请随时将其作为另一个答案发布。