Hoang Nguyen Hoang Nguyen - 1 year ago 41
C++ Question

Redefinition of a class C++

I'm working on a clock program and having some issue with the Clock external class and it gives me the error "redefinition of Clock::Clock()" in Clock.cpp file

Clock.cpp

#include <iostream>
#include <iomanip>
#include "Counter.h"
#include "Clock.h"

using namespace std;

Clock::Clock()
{
}

void Clock::Tick() {
_seconds.Increment();
if (_seconds.Value() == 60)
{
_seconds.Reset();
_minutes.Increment();
if (_minutes.Value() == 60)
{
_minutes.Reset();
_hours.Increment();
if (_hours.Value() == 24)
_hours.Reset();
}
}
}

void Clock::Reset()
{
_hours.Reset();
_minutes.Reset();
_seconds.Reset();
}

void Clock::PrintTime()
{
cout << setfill('0') << setw(2) << _hours.Value() << ":";
cout << setfill('0') << setw(2) << _minutes.Value() << ":";
cout << setfill('0') << setw(2) << _seconds.Value();
}


Clock.h

#ifndef CLOCK_H
#define CLOCK_H

class Clock
{
private:
Counter _hours;
Counter _minutes;
Counter _seconds;

public:
Clock(): _hours("hours"), _minutes("minutes"), _seconds("seconds"){};
void Tick();
void Reset();
void PrintTime();
};

#endif // CLOCK_H


The header guard is included but the compiler keeps giving the error :/
Any helps would be greatly appreciated.

Tas Tas
Answer Source

As @Craig Young points out in the comments, you've already implemented your Clock constructor.

Clock(): _hours("hours"), _minutes("minutes"), _seconds("seconds"){};

Simply change your header file so that so it only declares the constructor:

Clock();

And implement it in the source file:

Clock::Clock(): _hours("hours"), _minutes("minutes"), _seconds("seconds")
{
}

Keep your declarations in your header file, and implementations in your source file.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download