4

I am having issues getting this piece of code to compile. I am compiling with Eclipse on OS X 10.6. The problem seems to occur only when using vectors. I cannot seem to use the push_back function at all. 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 would have anything to do with how Eclipse is setup but it also seems that if I use the code located here, in place of my vector calls, it still compiles with the same error.

3 Answers 3

10

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);

... is a statement! It must live in a function :)

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

... will work.

Sign up to request clarification or add additional context in comments.

3 Comments

And I am officially a noob :) Thanks for the help, I am new to C++ and didn't know this fact.
Technically the rest are initializations. Assignments wouldn't be allowed either.
@UncleBen & @Kornel - what makes those legal outside a function is that they are definitions.
4

You can't have a statement outside of a function. So this line:

 lines.push_back(lp);

needs to be placed in a function.

It's okay to have definitions outside of a function, which is why these lines are okay:

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

Comments

4

Unless it's a typo, you have code in the open, outside of any function. This is not allowed in C++. You have to put it in a function or method instead. If you want it to run right away, put it in an int main() { ...}.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.