发布声明extern类对象 [英] Issue declaring extern class object

查看:445
本文介绍了发布声明extern类对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我先开始说我在google上更具体地搜索了答案。

Let me start by saying I've extensively searched for answers on google and more specifically here.

事实是我实际上(至少我认为我)发现有类似问题的人,虽然给他们的答案给了我另一个问题。

The thing is I actually (at least I think I did) found people with similar problems, though the answer given to them gave me another problem.

我使用Visual Studio 2010 Express和使用SFML库(虽然我不认为这最后一部分是相关的)

I'm using Visual Studio 2010 Express and working with SFML libary (though i do not think this last part is relevant)

所以这里:

我有一个名为player的源文件。 cpp它拥有类播放器和我有一个头文件(包括在所有源文件中)称为cc.h(命令和控制),它保存所有必要的包括和外部变量/函数。基本代码可以总结如下:

I have a source file called player.cpp which holds class Player and I have a header file (included in all source files) called cc.h(command and control) that holds all the necessary includes and external variables/functions. The essential code can be summed up in the following:

Player.cpp:

Player.cpp:

#include "cc.h"
class Player
{
private:

//some variables here

public:

//more variables and some functions

}john;//example instance

cc.h:

#pragma once

//some #includes
//some externs

extern Player john;

现在在cc.h中,Player的下划线是一个错误,表示它是一个 undefined标识符,但是有时候,visual studio不会将其标记为错误,而是将其识别为类,但不能将john识别为对象/实例(我希望这种方式)同一类。
此外,在编译第一个错误时,它显示为错误C2146:语法错误:缺少';'在标识符'john'

Now in cc.h the word Player is underlined as a mistake saying it is an undefined identifier , but only sometimes, other times visual studio doesn't mark it as a mistake, instead it recognizes it as a class but doesn't recognize john as an object/instance (i hope it's called this way) of that same class. Furthermore, at compiling the first error it shows is "error C2146: syntax error : missing ';' before identifier 'john'" at the line of the extern declaration of john, in cc.h, which apparently (to me) does not make any sense.

推荐答案

在全局声明中, cc.h不会帮助你,我猜 - 因为你声明它从其他地方(除了Player.cpp)访问它,但为此,你需要方法签名 - 一旦你想访问

The global declaration in cc.h would not help you, I guess - because you declare it to access it from else where (other than Player.cpp), but for this you need the method signatures - a soon as you want to access john from elsewhere and thus include Player.cpp, you get duplicates symbols.

请考虑创建一个播放器。 h 文件,其中只声明类和方法签名,如下所示:

Please consider creating a Player.h file where only the class and method signatures are declared - like this:

#ifndef PLAYER_H_
#define PLAYER_H_

class Player
{
     void doSomething();
};
#endif

并将其添加到cc.h:

and add this to cc.h:

#include <Player.h>
extern Player john;

和您的Player.cpp

and in your Player.cpp

#include <Player.h>

Player john;

void Player::doSomething()
{
    //...
}

这将确保 Player 签名是已知的,并且全局声明有效的实例。

This makes sure that the Player signatures are known and a valid instance is declared globally.

这篇关于发布声明extern类对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆