2

我正在使用 Visual Studio 2005。我创建了一个基于 MFC 的控制台应用程序,名为“StdAfx 依赖”。IDE 为我创建了以下文件。

  1. 资源.h
  2. StdAfx 依赖.h
  3. 标准数据文件
  4. StdAfx 依赖.cpp
  5. stdafx.cpp

CHelper我用 Helper.h 和 Helper.cpp添加了另一个类,如下所示。

助手.h:

#pragma once

class CHelper
{
public:
    CHelper(void);
    ~CHelper(void);
};

助手.cpp

#include "StdAfx.h"
#include "Helper.h"

CHelper::CHelper(void)
{
}

CHelper::~CHelper(void)
{
}

CHelper我在主函数中创建了一个对象;为了实现这一点,我在 StdAfx Dependancy.cpp 的第一行添加了 Header.h 文件,如下所示;我得到了以下错误。

d:\codes\stdafxdependancy\stdafxdependancy\stdafxdependancy.cpp(33):错误 C2065:'CHelper':未声明的标识符
d:\codes\stdafxdependancy\stdafxdependancy\stdafxdependancy.cpp(33):错误 C2146:语法错误:缺少 ';' 在标识符 'myHelper'
d:\codes\stdafxdependancy\stdafxdependancy\stdafxdependancy.cpp(33) 之前:错误 C2065:'myHelper':未声明的标识符

但是当我在 之后包含它时stdafx.h,错误就消失了。为什么?

// Stdafx dependancy.cpp : Defines the entry point for the console application.
//

#include "Helper.h"

#include "stdafx.h"
#include "Stdafx dependancy.h"

// #include "Helper.h" --> If I include it here, there is no compilation error

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// The one and only application object

CWinApp theApp;

using namespace std;

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
    int nRetCode = 0;

    // initialize MFC and print and error on failure
    if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
    {
        // TODO: change error code to suit your needs
        _tprintf(_T("Fatal Error: MFC initialization failed\n"));
        nRetCode = 1;
    }
    else
    {
        CHelper myHelper;
    }

    return nRetCode;
}
4

2 回答 2

5

这个链接必须给你一些线索。 stdafx.h 的目的

之前定义的行 #include "stdafx.h"会被编译器忽略。因此,如果您想实际包含这些文件,那么您需要在#include "stdafx.h".

希望很清楚。

于 2010-06-22T06:08:35.120 回答
1

除了 ckv 的回答之外,在“stdafx.h”之前包含头文件几乎没有意义,因为任何重要的头文件都将包含其中包含的框架类型(例如任何 MFC 类型)。

于 2010-06-22T06:12:32.883 回答