Home > OS >  Passing array into constructor parameter and creating an array of structs using the value of the arr
Passing array into constructor parameter and creating an array of structs using the value of the arr

Time:11-21

I am currently writing a class for a polygon that will be drawn onto the screen. My problem however, is that I am unable to figure out how to create an array of structs from an array of arrays (which hold integers, for x and y of each vertex). I am passing this array through the constructor. I assume my error is to do with trying to pass a pointer as an integer, although, after perilous research I can not seem to get my head around how to solve my error. I come from a background of dynamically typed languages (Js and Python mainly) and this is my first large project in a statically typed language. Any help is greatly appreciated.

struct Point {
    int x , y;
};
class Polygon
{
private:
    Point centre;

    Polygon(int x, int y, int vertices[]) {
        centre = {x, y};
        struct Point points[sizeof(vertices)/sizeof(vertices[0])] = {vertices};
    }

    //etc....
};
//Example of how it will be called in main.cpp
int main{
    Polygon polygon(0, 0, {{5,5}, {-5,5}, {5,-5}, {-5,-5}} );
}

CodePudding user response:

How about this?

struct Point {
    int x , y;
};

class Polygon
{
private:
    Point m_centre;
    std::vector <Point> m_vec_vertices;
public:

    Polygon(const Point& centre, const std::vector<Point> &vertices)
    :m_centre(centre), m_vec_vertices(vertices) { }

    //etc....
};

int main(){
    Polygon polygon({0, 0}, {{5,5}, {-5,5}, {5,-5}, {-5,-5}} );
}

You defined a point class, in the Polygon constructor why not use it instead of x and y right?

  • Related