Create new structures on the fly

I am (very) new to C ++ and am having trouble understanding structures. I use the sample code from the course, so I have:

struct Point { int x; int y; } 

In another bit of code, I want to write the following:

 drawLine(point1, new Point(x, y)); 

This does not work, and I understand that I am trying to declare a structure as if it were a class, but is there a way to do this? Currently, I have written a helper function that returns a point from x, y, but this seems to be roundabout.

+4
source share
3 answers

The problem is not that you are trying to declare a structure as if it were a class (in fact, there are very few differences between them in C ++ ).

The problem is that you are trying to build a Point from two ints , and there is no suitable constructor there. Here is how you can add one:

 struct Point { int x; int y; Point(int x, int y): x(x), y(y) {} }; 
+9
source

new returns a pointer. Just drawLine(point1, Point(x,y)) should work if you define an appropriate constructor for Point .

( drawLine(point1, *(new Point(x,y))) will also work, but will lead to a memory leak, each new should be balanced with delete .)

+3
source

The difference between structure and class in C ++ is not so great. Why don't you add a constructor to your structure?

0
source

Source: https://habr.com/ru/post/1346677/


All Articles