声明和访问全局对象

时间:2011-05-14 09:08:11

标签: c++ visual-studio-2008

众所周知的方法是声明int globalVar = 0然后使用它来使用它 - extern int globalVar;但是对于来自用户定义类的对象而言,这对我不起作用!

这是我所做的一个例子:

file1.cpp:

 #include "file2.h"  
class list { ....};  
 list * x ;       
//do something with x` 

file2.cpp:

class list;  
 extern list * x;  
//do something with x

这是我得到的错误:

error C2027: use of undefined type 'list'

如果我删除class list

error C2143: syntax error : missing ';' before '*' // in `extern list *x;`  
error C4430: missing type specifier - int assumed. Note: C++ does not support 
             default-int

感谢您的回答,现在就是这样:

#ifndef _ERRLIST_H_
#define _ERRLIST_H_
#include <queue>
#include <string>

struct errorStruct{
            int errLineNum;
            int errColNum ;
            char * errMessage;
    };
queue <errorStruct> errQueue; //error points here
class ErrList
{

public:
void pushError(int line,int col,char * message);
void popError();    
void printErrors();
int getSize();

};
#endif

但是我收到了这个错误:

error C2143: syntax error : missing ';' before '<'

4 个答案:

答案 0 :(得分:4)

应在头文件中使用

extern。将extern list *x放在头文件中实际上是对所有源文件的通知,即存在全局变量x并且在其他地方声明它。如果你不遵循这种方法,而是在源文件中编写extern list *x(就像@ Als那样),那么你实际上是在隐藏公告,而不是让所有源文件都清楚全局变量{ {1}}存在。然后会发生什么?稍后您可能会创建另一个源文件x,您可能会错误地声明名为file3.cpp的全局变量,这会导致链接器错误。

因此,解决方案是明确公告,正确的公告地点是头文件 - 因为这是所有其他公告的地方。

因此,您的代码应如下所示:

  • list.h:

    x
  • list.cpp:

    class list { ....};  
    extern list * x;//extern means the variable declaration is elsewhere
    
  • file1.cpp

    #include "list.h"
    
    list * x;   //alright, the variable declaration is here!
    
    //use x
    
  • file2.cpp

    #include "list.h"
    
    //use x - no need to write : extern list *x
    

对于与#include "list.h" //use x - no need to write : extern list *x 相关的错误,您应该使用其定义的名称空间queue限定它。写下这个:

std

同样,如果您使用 std::queue <errorStruct> errQueue; //^^^^^ mention the namespace (您已为其包含头文件),则写入string

答案 1 :(得分:1)

您的file2.cpp应包含定义为class list的标头。

myList.h

class list { ....};  

file1.cpp

#include "myList.h"
list * x ; 

file2.cpp

#include "myList.h"
extern list * x;  

答案 2 :(得分:0)

与任何类一样,编译器在使用之前需要查看其定义。将list的定义放在标题中,并将其包含在使用该列表的类中。这与全局对象无关。

答案 3 :(得分:0)

  

错误C2143:语法错误:缺少';'在'&lt;'

之前

它是“std :: queue&lt; errorStruct&gt;”,而不是“queue&lt; errorStruct&gt;”。