Push_back causes an error when using vectors in C ++

I'm having trouble compiling this piece of code. I am compiling with Eclipse on OS X 10.6. The problem, apparently, arises only when using vectors. I generally can not use the push_back function. Every time I try, I get the error "expected constructor, destructor or type conversion before." token. "Here are a few snippets of my code:

#include <GLUT/glut.h> #include <vector> #include <stdlib.h> #include <iostream> #include <math.h> using namespace std; enum Colour {BLACK =0, RED=1, BLUE=2, GREEN=3, PURPLE=4, ORANGE=5, CYAN=6, BLANK=7}; class Point { private: GLfloat xval, yval; public: Point(float x =0.0, float y = 0.0){ xval=x; yval=y; } GLfloat x() {return xval;} GLfloat y() {return yval;} }; class LinePoint { private: Point p; Colour cNum; public: LinePoint(Point pnt = Point(0,0), Colour c = BLACK){ cNum = c; p = pnt; } Point getPoint(){return p;} Colour getColour(){return cNum;} }; float turtleScale = 20; Point turtlePos = Point(300./turtleScale,200./turtleScale); LinePoint* lp = new LinePoint(turtlePos,BLACK); vector<LinePoint*> lines; lines.push_back(lp); 

I'm not sure if this will have anything to do with setting up Eclipse, but it also seems that if I use the code located here instead of my vector calls, it still compiles with the same error.

+4
source share
3 answers

Here:

 float turtleScale = 20; Point turtlePos = Point(300./turtleScale,200./turtleScale); LinePoint* lp = new LinePoint(turtlePos,BLACK); vector<LinePoint*> lines; 

... you use initializations, but this:

 lines.push_back(lp); 

... this statement! It must live in function :)

 int main() { lines.push_back(lp); } 

... will work.

+10
source

You cannot have an operator outside the function. So this line:

  lines.push_back(lp); 

must be placed in a function.

It's nice to have definitions outside the function, so these lines are in order:

 float turtleScale = 20; Point turtlePos = Point(300./turtleScale,200./turtleScale); LinePoint* lp = new LinePoint(turtlePos,BLACK); 
+4
source

If this is not a typo, you have the code open, outside of any function. This is not allowed in C ++. Instead, you should enter it in a function or method. If you want it to start immediately, put it in int main() { ...} .

+4
source

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


All Articles