其中一个头文件如下所示 -
#include "stdafx.h"
class AAA
{
public:
std::string strX;
std::string strY;
};
当我试图编译该项目时,我遇到了错误。
error C2011: 'AAA' : 'class' type redefinition
我程序中没有重新定义AAA
类的地方。我该怎么解决这个问题?
其中一个头文件如下所示 -
#include "stdafx.h"
class AAA
{
public:
std::string strX;
std::string strY;
};
当我试图编译该项目时,我遇到了错误。
error C2011: 'AAA' : 'class' type redefinition
我程序中没有重新定义AAA
类的地方。我该怎么解决这个问题?
将代码更改为类似这样的内容:
#ifndef AAA_HEADER
#define AAA_HEADER
#include "stdafx.h"
class AAA
{
public:
std::string strX;
std::string strY;
};
#endif
如果在某个源文件中多次包含此头文件,include guards 会强制编译器只生成一次类,因此不会出现 class redefinition
错误。
添加
#pragma once
在您的AAA.h文件顶部添加此内容即可解决问题。
像这样
#include "stdafx.h"
#pragma once
class AAA
{
public:
std::string strX;
std::string strY;
};
#pragma once
,但是直到我添加了一个宏定义才起作用: // does not work
#pragma once
// works with or without #pragma once
#ifndef _HEADER_AAA
#define _HEADER_AAA
//
// my code here....
//
#endif
我不知道如何解释这个,但对我来说这是一个解决方案。
有两种方法可以解决这个问题,但你不能同时使用两种方法。请确保用编译器指令将类定义包装起来,以便只编译一次类声明:
#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