2014-05-20 136 views
1

我在C++中定义了一个名为Date的简单类。我使用的IDE是Qt Creator。当我编译时,编译器说这个类中的每个函数都有“多个定义”。下面是在.cpp和.h文件:C++中与链接错误有关的多重定义错误

// date.h 

#ifndef DATE_H 
#define DATE_H 

#include <string> 

/* A class representing an earth day.*/ 

class Date { 

public: 
    /*construct a new day, initially assigned at Jan.1st.2000*/ 
    Date(); 

    /* take three numbers to create the date.*/ 
    Date(int cmonth,int cday, int cyear); 

    /*clean up memory allocated to this data type*/ 
    ~Date(); 

private: 
    int year; 
    int month; 
    int day; 
}; 

#endif // DATE_H 

`

// date.cpp 

#include "date.h" 

Date::Date(){ 
    year=2000; 
    month=1; 
    day=1; 
} 

Date::Date(int cmonth,int cday, int cyear){ 
    month=cmonth; 
    day=cday; 
    year=cyear; 
} 

/*clean up memory allocated to this data type*/ 
Date::~Date(){ 
    //automatic 
} 

样品错误消息: d:samplepath \ date.cpp:3:错误:`日期::日期的多个定义()”

可能导致错误(基本上什么)

一个可能的主要CPP:

#include <iostream> 

using namespace std; 

int main() { 
    int sum=0; 
    cout << sum << endl; 
    return 0; 
} 

我有米请确保我避免了与此消息相关的几个基本错误,即:

  • 我没有在标题中放置任何实现。
  • 我用#ifndef保护
  • 我做了关键字Date的全球搜索,没有发现任何冲突。
  • 我总是用一个新的版本编译

在这个类中的每个函数有一个错误“的多个定义”,但我不能告诉什么地方出了错。目前我正在做一个四肢全脸四肢手掌。任何帮助将不胜感激。

更新:事实证明,这确实是链接器错误。

SOURCES += $$files($$PWD/*.cpp) \ 
     date.cpp 

代码“date.cpp”第二行实际上是自动这里由Qt Creator的加入,如果您:Qt Creator中的.pro文件,我用下面的代码包含在源文件两次通过菜单创建新课程。

非常感谢这里的所有人为您的慷慨帮助!

+0

你确实需要定义一个析构函数,如果你没有什么可以销毁的话。 – tillaert

+3

这是唯一的Date类吗?尝试将你的类放入一个命名空间中。 – tillaert

+0

任何具有相同类的库? – Rakib

回答

1

我建你的代码与此QMAKE.pro文件,它内置了与预期输出(0)执行:

TEMPLATE = app 
CONFIG += console 
CONFIG -= qt 

SOURCES += main.cpp \ 
    date.cpp 

HEADERS += \ 
    date.h 
+0

我将修改.pro并稍后再回复 – Wayne

+0

是的,当我以这种方式更改.pro文件时。它确实有效。然后,我的.pro文件必须有错误。有什么建议么? – Wayne

+0

@Wayne我建议你编辑问题,现在你知道实际问题是什么。 – hyde

0

你确定这是一个编译器错误,而不是链接器错误?也许你已经包含了两次对象文件(在.pro文件中)。另外,尽量把在构造函数的声明默认值,而不是超载:

Date(int cmonth=2000,int cday=1, int cyear=1); 
+0

如果在.pro中包含两次头文件(#ifndef DATE_H,#define DATE_H ...)将保护该文件,前提是OP的源文件中不包含实现文件。 – TheDarkKnight

+1

@MrUser你应该避免使用默认值,因为它们在使用继承时会出现问题。最好使用参数列表。 'Date():year(2000),month(1),day(1){}' – tillaert

+0

感谢您的文体建议。但是,不,我没有在.pro文件中包含头文件。 – Wayne