使用typedef时可以重命名成员吗?

时间:2014-04-26 15:59:38

标签: c++ struct typedef member

我正在使用三个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;

现在我想使用此定义来表示轮播,但我不想以xyz来访问其成员,但是{{1 },yawpitch。是否可以通过roll重命名此类成员?还是有另一种方法不包括重新定义完整的结构及其成员?

2 个答案:

答案 0 :(得分:3)

不,因为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;
}

答案 1 :(得分:-1)

所以这就是我的观点:它可能并不完美,但允许同时轻松修改所有三个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)

我个人喜欢这个解决方案。这确实有点难以阅读,但我们只讨论基本的算术运算,代码并不是太花哨,你可以一目了然地看到哪些运算符被定义。

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

相关问题