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

use*_*272 13 c++ visual-studio-2005 class

其中一个头文件如下 -

#include "stdafx.h"

class AAA
{
public:
    std::string strX;
    std::string strY;
};
Run Code Online (Sandbox Code Playgroud)

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

error C2011: 'AAA' : 'class' type redefinition
Run Code Online (Sandbox Code Playgroud)

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

Ash*_*hot 35

将代码更改为以下内容:

#ifndef AAA_HEADER
#define AAA_HEADER

#include "stdafx.h"

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

#endif
Run Code Online (Sandbox Code Playgroud)

如果在某个源文件中多次包含此头文件,则include guard将强制编译器仅生成一次类,因此不会class redefinition出错.

  • AAA_HEADER只是用于标识文件的唯一字符串.在这里阅读有关包含警卫的信息http://stackoverflow.com/questions/8020113/c-include-guards (3认同)

Kev*_*ude 20

添加

#pragma once
Run Code Online (Sandbox Code Playgroud)

在AAA.h文件的顶部应该处理问题.

像这样

#include "stdafx.h"
#pragma once

class AAA
{
public:
    std::string strX;
    std::string strY;
};
Run Code Online (Sandbox Code Playgroud)

  • 是否应该更可能在文件的最顶部(第一行)而不包含某些内容? (2认同)

Sco*_*MVP 5

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