jb.
jb.

Reputation: 10341

Using vectors with objects error

It's been awhile since I've done C++ so I'm having a bit of trouble here. I'm getting this error on the line where I declare allQueue in the main file. I've obviously stripped out a lot of code that I don't think is required, if you need anything more let me know.

Compiling with

g++ mainFile.cpp MyClass.cpp extraObjectFile.o -o mainFile

Generates:

error: expected constructor, destructor, or type conversion before ‘<’ token

main file

#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <iostream>    
#include "MyClass.h"

vector<MyClass> allQueue;
int main()
{
   allQueue.push_back(new MyClass(100));
}

MyClass.cpp

#include "MyClass.h"

MyClass::MyClass(int start_priority)
{
    priority = start_priority;
}


int MyClass::getPriority()
{
    return priority;
}

MyClass.h

class MyClass
{
    int priority;
    public:
        MyClass(int);
        int getPriority();
};

Upvotes: 0

Views: 203

Answers (3)

Dmitriy Kachko
Dmitriy Kachko

Reputation: 2914

  1. Use std::vector, not simply vector.

  2. Operator new returns a pointer to MyClass, not an object itself. You need make a vector of pointers (vector<MyClass*>) or you need to use MyClass() constructor like this

    MyClass m(100); allQueue.push_back(m);

or simply that

allQueue.push_back(mMyClass(100));

Upvotes: 1

cli_hlt
cli_hlt

Reputation: 7164

Ok, first thing to note: When you post an error message, please post the full error message your compiler gave you. Otherwise, nobody might be able to help you.

Secondly, the answer to your question:

Use

std::vector<MyClass> allQueue;

in your main.cpp file. And do a

allQueue.push_back(MyClass(100));

to add objects. Consider implementing a copy constructor for MyClass also.

Upvotes: 6

zvrba
zvrba

Reputation: 24546

Change vector to std::vector.

Upvotes: 1

Related Questions