我在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文件,我用下面的代码包含在源文件两次通过菜单创建新课程。
非常感谢这里的所有人为您的慷慨帮助!
你确实需要定义一个析构函数,如果你没有什么可以销毁的话。 – tillaert
这是唯一的Date类吗?尝试将你的类放入一个命名空间中。 – tillaert
任何具有相同类的库? – Rakib