Reputation: 3
I'm trying to create a vector that can hold several already existing objects but i'm having trouble with it. In visual studio it says "this declaration has no storage class or type specifier".
Here is the code:
#include <iostream>
#include <vector>
#include <string>
struct test {
int id;
test(int i) {
id = i;
}
};
test obj1(1);
test obj2(2);
test obj3(3);
std::vector<test> egg;
egg.push_back(obj1);
egg.push_back(obj2);
egg.push_back(obj3);
int main() {}
Upvotes: 0
Views: 73
Reputation: 22152
You cannot write expression statements such as egg.push_back(obj1);
at file/namespace scope, in contrast with declarations/definitions such as test obj1(1);
. Expression statements can only be used at block scope, i.e. inside a function body. For example
int main() {
egg.push_back(obj1);
egg.push_back(obj2);
egg.push_back(obj3);
}
Also avoid using global variables and put all variable declarations/definitions in a local scope as well:
int main() {
test obj1(1);
test obj2(2);
test obj3(3);
std::vector<test> egg;
egg.push_back(obj1);
egg.push_back(obj2);
egg.push_back(obj3);
}
Also, unrelated to question, use the member initializer list of the constructor to initialize members, rather than assigning to the members in the constructor body:
test(int i) : id(i) {
}
Upvotes: 2
Reputation: 152
As zach has said, there is code outside of your main method. std::vector<test> egg;
is allowed outside of int main
but a function like egg.push_back(obj1);
is not
revised code:
#include <iostream>
#include <vector>
#include <string>
struct test {
int id;
test(int i) {
id = i;
}
};
test obj1(1);
test obj2(2);
test obj3(3);
std::vector<test> egg;
int main() {
egg.push_back(obj1); //moved to main
egg.push_back(obj2); //moved to main
egg.push_back(obj3); //moved to main
}
Upvotes: 0
Reputation: 792
I think the issue with that program is that all of your code is outside of the main method, and thus the compiler doesn't know what to do with it.
Upvotes: 3