Reputation: 690
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?
Upvotes: 3
Views: 24344
Reputation: 1112
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;
}
Upvotes: 5
Reputation: 108978
Using C, this works for me
typedef struct { float x; float y; float z; } Vertex;
int main(void) {
Vertex a = {42, -42, 0};
if (a.x + a.y + a.z == 0) return 1; /* warning about comparing floating point values */
return 0;
}
Upvotes: 1
Reputation: 101456
does this have to be declared somewhere where it can be seen by main?
Yes. Typically the class or struct is declared in a header file, which you #include
in whatever translation unit (c file) you use it in.
Upvotes: 1