【发布时间】:2017-07-24 23:14:00
【问题描述】:
假设我有一个班级Person
TestClass.h:
#pragma once
class Person {
int age;
std::string name;
public:
Person(int age, const std::string& name);
private:
int getAge();
std::string getName();
};
TestClass.cpp
#include "stdafx.h"
#include "TestClass.h"
Person::Person(int age, const std::string& name) : age(age), name(name) {};
int Person::getAge() {
return age;
}
std::string Person::getName() {
return name;
}
对于这个例子,代码编译。
但是,如果我在TestClass.cpp 的第 1 行和第 2 行之间切换并包含
stdafx.h 第二,由于某种原因,我得到以下编译错误:
'Person': is not a class or namespace name
missing type specifier - int assumed. Note: C++ does not support default-int
'Person': constructor initializer lists are only allowed on constructor definitions
'Person': is not a class or namespace name
'Person': function should return a value; 'void' return type assumed
'age': undeclared identifier
'Person': is not a class or namespace name
'name': undeclared identifier
显然,如果我首先包含 stdafx.h,我不会有任何问题,但我似乎无法理解为什么会发生这种情况。任何帮助将不胜感激。
【问题讨论】:
-
stdafx.h 是一个奇怪的特定于 Visual Studio 的文件,具有特殊的含义和行为:What's the use for “stdafx.h” in Visual Studio? 如果它坚持要先行,那就顺其自然吧。 Visual Studio 不会编译 stdafx.h 之前文件中的任何内容。因为他们这么说。
-
@user4581301 这就是我要找的。我知道 stdafx.h 是一个 VS 特定文件,我认为这可能是故意的,但我找不到任何明确表示在文件包含之前什么都不能出现的东西。谢谢。
-
与您一起讨论缺乏来自马口的解释。我能做的最好的权威答案是上一个链接
-
如果你不需要stdafx.h,最好选择empty project,同时新建一个。这样标准 C++ 文件将正常编译而不包括 stdafx.h
-
@LưuVĩnhPhúc 我知道如何让代码编译,问题的关键是我可以理解为什么如果 stdafx.h 不在第一行,代码将无法编译。这是假设需要 stdafx.h。
标签: c++ visual-studio stdafx.h