conversion of structure to a class

Hi I am doing an assignment and I am supposed to do using classes. As I get really confused with C++ I am just stuck. Could you help me in changing the following structure into c class?? This is just an example.. Thank you.

typedef struct Normal
{
Normal() : x(0), y(0), z(0) {}
Normal(float xx) : x(xx), y(xx), z(xx) {}
Normal(float xx, float yy, float zz) : x(xx), y(yy), z(zz) {}
Normal operator * (const float &r) const
{ return Normal(x*r, y*r, z*r); }
Normal operator - () const
{ return Normal(-x, -y, -z); }
float x, y, z;
};
Isn't that already a class?
It is mal-formed. A typedef requires the following format:

typedef existing-type alias-type;

He is missing the alias type. The usual way to do this thing is:

1
2
3
4
5
typedef struct Normal_tag
  {
  struct Normal_tag* foo;  // The alias type "Normal" doesn't exist yet, but "struct Normal_tag" does
  }
Normal;


In C++ the struct namespace is merged into the identifier namespace, so you can forget all that typedef stuff..

1
2
3
4
5
6
7
struct Normal
  {
  Normal* foo;  // Yep, this is OK without the struct keyword.
  Normal(): x(0), y(0), z(0) {}  // Constructors and other C++ things OK too...
  ...
  float x, y, z;
  };


As a final remark, I'm not sure I would call my class "Normal". A normal is a specific type of vector. But not every vector is a normal.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct Vector
  {
  float x, y, z;  // note 1
  Vector( float x = 0.0, float y = 0.0, float z = 0.0 ): x(x), y(y), z(z) { }  // note 2
  Vector operator * ( const float& k ) const
    {
    return Vector( x * k, y * k, z * k );
    }
  ...
  };

Vector operator * ( const float& k, const Vector& v )  // note 3
  {
  return v * k;
  }

Note 1: I personally think it is a good idea to put fields first and methods last. Your prof may disagree. (There is no "right" way.) I just think it makes reading the class easier.

Note 2: The utility of a constructor to assign the same value to all three vector components is not very high. The constructor I recommend for you here functions as both the default constructor and the components-to-vector constructor.

Note 3: Don't forget to overload both ways. This way, you can place the scalar both before and after the vector:
1
2
3
4
Vector v( 1, 2, 3 );
Vector u = v * 5;
Vector w = 5 * v;
// u == w 
Notice also how the external operator works by simply calling the already-defined class operator.

Hope this helps.
Last edited on
thanks a lot...
Topic archived. No new replies allowed.