【问题标题】:Define statement expected a declaration C++定义语句需要一个声明 C++
【发布时间】:2015-04-10 17:58:25
【问题描述】:

好的,所以我已经缩小了与 #ifndef 和/或 #define 关键字有关的问题。

我还有 2 个其他 .h 文件,没有错误的文件和没有错误的文件之间的唯一区别是 #ifndef EMPLOYEE_H#define EMPLOYEE_H 上的语法突出显示在有错误的文件上交换。

虽然我不确定这意味着什么(我正在使用 Visual Studio),但它导致我所有其他定义的语句变白,就像它们被包含在某些语句中一样。

我不知道怎么了!

这是我的代码:

//Specification file for the Employee Class
#ifndef EMPLOYEE_H
#define EMPLOYEE_H

#include <string>

using namespace std;


class Employee

{

protected:
//Employee name
string name;
//Required Training hours
string emNum;
//Completed training hours
string hireDate;


public:
//Default Constructor
Employee()
{
    name = " ";
    emNum = " ";
    hireDate = " ";
}

//Constructor
Employee(string aName, string aNumber, string aDate)
{
    name = aName;
    emNum = aNumber;
    hireDate = aDate;
}

//mutators
void setName(string empName) { name = empName; }
void setEmployeeNumber(string empNumber) { emNum = empNumber; }
void setHireDate(string date) { hireDate = date; }

//accessors
string getName() const { return name; }
string getEmployeeNumber() const { return emNum; }
string getHireDate() const { return hireDate; }


#endif



};

我的错误是:

错误 1 ​​错误 C2059:语法错误:'}'

错误 2 错误 C2143:语法错误:缺少 ';'在'}'之前

4 IntelliSense:需要声明

块引用

错误也突出了 }; 在最后。

【问题讨论】:

    标签: visual-studio c++11 ifndef


    【解决方案1】:

    问题在于位于类定义中的#endif 指令(在}; 代码之前),因此此头文件的第二次包含将仅包含导致错误的}; 代码你明白了。

    顺便说一句,您可以简单地在文件开头使用#pragma once,而不是使用#ifndef 模式,这具有相同的效果。您可以在here 中阅读更多关于pragma once 与使用包含守卫的信息。

    【讨论】:

    • 非常感谢!!我把它放在外面,现在课程工作得很好,再次感谢!
    猜你喜欢
    • 2018-09-26
    • 1970-01-01
    • 2021-03-04
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多