gpt4 book ai didi

c++ - C++ 中与链接错误相关的多重定义错误

转载 作者:太空宇宙 更新时间:2023-11-04 11:33:23 31 4
gpt4 key购买 nike

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

// 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: 错误:`Date::Date()' 的多重定义

一个可能导致错误的主要 cpp(基本上是任何东西):

#include <iostream>

using namespace std;

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

我已确保我避免了一些与此消息相关的基本错误,即:

  • 我没有在 header 中放置任何实现。
  • 我使用#ifndef 进行保护
  • 我对关键字 Date 进行了全局搜索,没有发现任何冲突。
  • 我总是使用新构建来编译

这个类中的每个函数都有一个“multiple definition of”的错误,但是我也说不出哪里出了问题。目前我正在做全肢四面手掌。任何帮助将不胜感激。

更新:事实证明,这确实是一个链接器错误。在 Qt Creator 的 .pro 文件中,我包含了两次源文件,代码如下:

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

如果您通过其菜单创建新类,则第二行代码“date.cpp”实际上是由 Qt Creator 自动添加到此处的

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

最佳答案

我用这个 qmake .pro 文件构建了你的代码,它构建并执行了预期的输出 (0):

TEMPLATE = app
CONFIG += console
CONFIG -= qt

SOURCES += main.cpp \
date.cpp

HEADERS += \
date.h

关于c++ - C++ 中与链接错误相关的多重定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23753869/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com