简体   繁体   中英

How do I create a vector that holds objects?

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() {}

我认为该程序的问题在于您的所有代码都在 main 方法之外,因此编译器不知道如何处理它。

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 , ie 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) {
}

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM