Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating my own 'data type'

Tags:

c++

I want to be able to create a type that has 3 floats (x,y,z). I have tried:

typedef struct
{
 float x;
 float y;
 float z;
} Vertex;

But that didn't work.

Does this have to be declared somewhere where it can be seen by main? How would I go about creating getter methods and other methods for a type I have made?

like image 656
CurtisJC Avatar asked Mar 11 '26 14:03

CurtisJC


1 Answers

How I'd do it in C++. See main() for example usage. N.B. This hasn't been compiled or tested.

#include <iostream>

class Vertex
{
public:
  // Construction
  Vertex(float x,float y, float z) : x_(x), y_(y), z_(z) {}

  // Getters
  float getX() const {return x_;}
  float getY() const {return y_;}
  float getZ() const {return z_;}

  // Setters
  void setX(float val) {x_ = val;}
  void setY(float val) {y_ = val;}
  void setZ(float val) {z_ = val;}
private:
  float x_;
  float y_;
  float z_;
};

int main()
{
  Vertex v(6.0f,7.2f,3.3f);
  v.setZ(7.7f);
  std::cout < "vertex components are " << v.getX() << ',' << v.getY() << ',' << v.getZ() << std::endl;
}
like image 84
PeteUK Avatar answered Mar 14 '26 02:03

PeteUK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!