简体   繁体   English

C ++未知名称类型

[英]C++ unknown name type

I have a header file defining some parameters. 我有一个定义一些参数的头文件。 I have defined some of the parameters as extern. 我已经将某些参数定义为extern。 My program works fine with other data types such as double and int, except when I try to add vector variables. 我的程序可以与其他数据类型(例如double和int)一起正常工作,除非尝试添加矢量变量。 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. 当我尝试使用clear方法清除向量时,编译器给出了一个错误消息,指出该未知类型。 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: PS我最初试图使用以下方法为此向量分配一些值:

my_vec[0] = 1;

but the compiler says that C++ requires a type specifier for all declarations. 但是编译器说C ++要求所有声明都使用类型说明符。 I googled this error, but I don't understand because I am specifying the type of my_vec. 我用谷歌搜索了这个错误,但是我不明白,因为我指定了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(); 您不能在函数外部执行语句-这就是您要使用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; 没关系clear()是向量类的方法-调用方法(而不是构造变量)是一条语句,就像x = 1; . Those belong in functions. 这些属于功能。

You have to put your statement somewhere in your main() , eg: 您必须将语句放在main()某个位置,例如:

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. 或确保以您希望的方式构建my_vec

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. 编辑: OP询问我们是否可以以某种方式解决此限制。 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. 但是有可能:我们可以使用static block ,它可以在C ++中实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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