错误 C2011: '' : 'class' 类型重定义

30

其中一个头文件如下所示 -

#include "stdafx.h"

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

当我试图编译该项目时,我遇到了错误。

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

我程序中没有重新定义AAA类的地方。我该怎么解决这个问题?


6
你需要使用预编译指令来避免重复包含头文件。 - juanchopanza
5个回答

55

将代码更改为类似这样的内容:

#ifndef AAA_HEADER
#define AAA_HEADER

#include "stdafx.h"

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

#endif

如果在某个源文件中多次包含此头文件,include guards 会强制编译器只生成一次类,因此不会出现 class redefinition 错误。


AAA_HEADER是AAA.h文件吗? - user3164272
3
AAA_HEADER只是一个唯一的字符串,用于识别文件。在这里阅读有关包含保护的信息:https://dev59.com/4msz5IYBdhLWcg3wQFe2 - Ashot
这个解决方案的好处是它适用于所有的C++编译器,而不仅仅是微软的。 - empty

37

添加

#pragma once

在您的AAA.h文件顶部添加此内容即可解决问题。

像这样

#include "stdafx.h"
#pragma once

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

3
应该把它放在文件的最顶部(第一行)而不是某些包含语句之后,这样更合适吗? - Sandburg

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

1
我今天在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

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


0

有两种方法可以解决这个问题,但你不能同时使用两种方法。请确保用编译器指令将类定义包装起来,以便只编译一次类声明:

#include "stdafx.h"

#pragma once

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

-或-

   #include "stdafx.h"
    
    #ifndef AAA_HEADER_
    #define AAA_HEADER_
    
    class AAA
    {
    public:
    
        std::string strX;
        std::string strY;
    
    };
    
    #endif

另外:请注意类导入语句应该放在文件顶部。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接