C++ "undefined reference to..."

C++ "undefined reference to..."

本文关键字:to reference undefined C++      更新时间:2023-10-16

我不知道为什么我的代码出错了,我需要一些帮助。

首先,代码:

Timer.h:

#include [...]
class Timer {
    public:
        [...]
        Timer operator+(double);
        [...]
    private:
        [...]
        void correctthedate(int day, int month, int year);
        [...]
};

Timer.cc:

#include "Timer.h"
using namespace std;
[...]
void correctthedate(int day, int month, int year) {
    [...]
}
[...]
Timer Timer::operator+(double plush) {
    [...]
    correctthedate(curday, curmonth, curyear);
    return *this;
}

当我尝试编译时,我得到错误:

Timer.o: In function `Timer::operator+(double)':
Timer.cc:(.text+0x1ad3): undefined reference to `Timer::correctthedate(int, int, int)'

有正确方向的指示吗?谢谢!

下一行:

void correctthedate(int day, int month, int year) {

应该读

void Timer::correctthedate(int day, int month, int year) {

否则你只是定义了一个不相关的函数correctthedate()

Write

void Timer::correctthedate(int day, int month, int year) {

您的correctthedate定义是一个自由函数,尽管没有原型。您必须使用Timer::

限定名称

替换为

void correctthedate(int day, int month, int year) {
与这个:

Timer::correctthedate(int day, int month, int year) {

在您的版本中,correctthedate只是一个普通的函数,它恰好与Time的一个方法具有相同的名称。Time::correctthedate是一个完全不同的函数(方法),它没有定义,所以链接器抱怨它找不到它。

你的头声明了一个Timer::operator+和一个Timer::correctthedate函数。
您的cpp定义了Timer::operator+::correcttehdate函数。
链接器找不到Timer::correctthedate

答案是将void correctthedate(int...改为void Timer::correctthedate(int...

相关文章: