简体   繁体   中英

C++ unknown name type

I have a header file defining some parameters. I have defined some of the parameters as extern. My program works fine with other data types such as double and int, except when I try to add vector variables. The declaration in header file is

extern std::vector<double> my_vec;

In my main file, I am constructing the vector using this code:

std::vector<double> my_vec(3,0);

When I try to clear the vector using the clear method, the compiler is giving an error saying that unknown type. I am not even sure how to debug this. Can someone help?

PS I was originally trying to assign some values to this vector using:

my_vec[0] = 1;

but the compiler says that C++ requires a type specifier for all declarations. I googled this error, but I don't understand because I am specifying the type of my_vec.

Edit: example:

main.cpp
#include "params.h"
#include <vector>

std::vector<double> my_vec(3,0);

my_vec.clear();
// edit: my_vec[0] = 1; this also produces an error

int main(){
    return 0;
}

params.h
#include <vector>

extern std::vector<double> my_vec;

Error message:

main.cpp:6:1: error: unknown type name 'my_vec'
my_vec.clear();
^
main.cpp:6:7: error: cannot use dot operator on a type
my_vec.clear();
      ^
2 errors generated.

You can't execute statements outside of a function - which is what you're trying to do with my_vec.clear(); . It doesn't matter that clear() is a method of the vector class - invoking a method (as opposed to constructing a variable) is a statement, just like x = 1; . Those belong in functions.

You have to put your statement somewhere in your main() , eg:

int main(){
    my_vec.clear();
    return 0;
}

or make sure and construct my_vec the way you want it to look like, to begin with.

Also, more generally, you should avoid global variables if you don't really need them. And - you very rarely do. See:

Are global variables bad?

Edit: OP asks whether we can get around this restriction somehow. First - you really shouldn't (see what I just said). But it is possible: We can use a static block , which is implementable in C++, sort of.

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