错误:类(C++)的重新定义

Error: Redefinition of Class (C++)

本文关键字:新定义 定义 C++ 错误      更新时间:2023-10-16

我正试图弄清楚为什么会出现以下错误:

错误:重新定义"TimeDuration"

// TimeDuration.cpp
#define HOUR 3600
#define MIN 60
#include <iostream>
#include <string>
#include "TimeDuration.h"
using namespace std;
TimeDuration::TimeDuration() {
    seconds = 0;
}
void TimeDuration::setDuration(const int sec) {
    seconds = sec;
}
void TimeDuration::display() {
    // Some code to display the time
}

错误显示在我的头文件中。

// TimeDuration.h
class TimeDuration {
    private:
        int seconds;
    public:
        TimeDuration();                     
        void setDuration(const int sec);    
        void display();                     
};

错误可能是因为TimeDuration.h 中没有标头保护

头保护的标准方法是在文件写入的开头:

#ifndef TIME_DURATION_H
#define TIME_DURATION_H

在文件末尾:

#endif

您可以使用

#pragma once

在TimeDuration.h文件中,在起始处