【问题标题】:error C2011: '' : 'class' type redefinition错误 C2011:“”:“类”类型重新定义
【发布时间】:2014-11-01 01:12:50
【问题描述】:

其中一个头文件如下-

#include "stdafx.h"

class AAA
{
public:
    std::string strX;
    std::string strY;
};

当我尝试编译项目时,我得到了错误

error C2011: 'AAA' : 'class' type redefinition

在我的程序中没有其他地方我重新定义了 AAA 类。我该如何解决这个问题?

【问题讨论】:

  • 你需要使用include保护。

标签: c++ class visual-studio-2005


【解决方案1】:

把代码改成这样:

#ifndef AAA_HEADER
#define AAA_HEADER

#include "stdafx.h"

class AAA
{
public:
    std::string strX;
    std::string strY;
};

#endif

如果你在某个源文件中多次包含这个头文件,包含守卫将强制编译器只生成一次类,因此它不会给出class redefinition 错误。

【讨论】:

  • AAA_HEADER 是 AAA.h 文件吗?
  • AAA_HEADER 只是用于标识文件的唯一字符串。在此处阅读有关包含警卫的信息stackoverflow.com/questions/8020113/c-include-guards
  • 这个解决方案的好处是它适用于所有 C++ 编译器,而不仅仅是微软的。
【解决方案2】:

除了建议的包含保护之外,您还需要将#include "stdafx.h" 从标题中移出。放在cpp文件的顶部。

【讨论】:

    【解决方案3】:

    添加

    #pragma once
    

    到您的 AAA.h 文件的顶部应该可以解决问题。

    喜欢这个

    #include "stdafx.h"
    #pragma once
    
    class AAA
    {
    public:
        std::string strX;
        std::string strY;
    };
    

    【讨论】:

    • 是否应该更可能在文件的最顶部(第一行)而不是在某些包含之后?
    【解决方案4】:

    我今天在VS 2017中遇到了这个问题。我添加了#pragma once,但是直到我添加了宏定义它才起作用:

        // does not work    
        #pragma once
            
        // works with or without #pragma once
        #ifndef _HEADER_AAA
        #define _HEADER_AAA
        //
        // my code here....
        //
        #endif
    

    我不知道如何解释,但这对我来说是一个解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-23
      • 1970-01-01
      • 1970-01-01
      • 2016-09-27
      相关资源
      最近更新 更多