I am (very) new to C++, and am having some issues understanding structs. I'm using example code from a course, so I ha开发者_StackOverflow中文版ve:
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 struct as if it were a class, but is there a way to do this? I have currently written a helper function which returns a Point from an x,y, but this seems roundabout.
The problem isn't that you're trying to declare a struct as if it were a class (in fact, there's very little difference between the two in C++).
The problem is that you're trying to construct a Point
from two ints
, and there ins't a suitable constructor. Here is how you can add one:
struct Point {
int x;
int y;
Point(int x, int y): x(x), y(y) {}
};
new
returns a pointer. Just drawLine(point1, Point(x,y))
should work if you define the appropriate constructor for Point
.
(drawLine(point1, *(new Point(x,y)))
would also work, but would introduce a memory leak; every new
should be balanced by a delete
.)
The difference between struct and class in c++ is not that huge. Why don't you add a constructor to your struct?
精彩评论