C ++错误此声明没有存储类或类型说明符 [英] C++ Error this declaration has no storage class or type specifier

查看:217
本文介绍了C ++错误此声明没有存储类或类型说明符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<map>
using namespace std;
typedef map<char,char> charMap;

//take a global variable for this map
charMap g_charMap;
int i; //it is working fine
g_charMap.insert(make_pair('{','}'));//Above mentioned Error is shown in this line

int main()
{
  //some stuff is there.
}





任何人都可以告诉我的理由和解决方案?



Can anyone please tell me reason and solution?

推荐答案

你不能在函数声明之外编写普通代码。将它移到Main方法中:

You can't write "normal" code outside a function declaration. Move it inside the Main method:
charMap g_charMap;
int main()
   {
   g_charMap.insert(make_pair('{','}'));
   //some stuff is there.
   }


全局对象仅在全局范围中提供其construcor和析构函数的调用。

尝试将调用放入主函数:)
A global object does provide its construcor's and destructor's calls only, in the "global scope".
Try to place the call into your main function :)


在网上搜索单例模式...



基本上不使用全局变量,而是使用静态函数在返回通常在第一次使用时创建的对象的唯一实例的类中。



在多线程程序锁中也可以用于同步,或者您可以确保实例是在任何额外的线程之前创建的。



或者嵌入地图在另一个带有构造函数的对象中(或从地图派生)将允许你填充该静态构造时的对象来自容器对象构造函数(或派生类构造)如果您选择该选项,请选择。)



请记住,您应该始终避免使用全局变量。在许多情况下,Singleton是一个很好的妥协。



最后,有一个简单的解决方案来填充主要的地图。通常,您还希望避免在main之前执行复杂的代码,因为它更难以正确处理可能在此阶段发生的错误。
Search for singleton pattern on the web...

Essentially instead of using a global variable, you use a static function Inside a class that return the unique instance of the object which is typically created on the first use.

In multithreaded program locks can also be used for synchronization or you might ensure that the instance is created before any additionnal thread.

Alternatively embedding the map Inside another object with a constructor (or deriving from the map) would allows you to fill that static object at construction time from container object constructor (or derived class constructor if you opt for that option).

Remember that you should always avoid global variables. Singleton is a good compromise in many cases.

Finally, there is alwaus the simple solution to fill the map from the main. In general, you also want to avoid complex code to be executed before main as it make harder to properly handle errors that might occurs at this stage.


这篇关于C ++错误此声明没有存储类或类型说明符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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