I have my base class Gate, whilst the derived class is AND (XOR etc.). The virtual function I have in my base class is for determining an output, but when I prototype it in AND.h and try and implement it with AND.cpp I get the redefinition error on compile. I am sure I have included everything properly.

Gate header

#ifndef GATE_H
#define GATE_H

class Gate{
    public:
        // various functions etc.

        virtual bool output();   // **PROBLEM FUNCTION**

};

#endif

Gate source

#include "Gate.h"

//*various function declarations but not virtual declaration*

Derived class "AND"

#ifndef AND_H_INCLUDED
#define AND_H_INCLUDED

class AND: public Gate{
public:
    bool output(bool A, bool B){}
};
#endif // AND_H_INCLUDED

and where my IDE puts my error occuring in the AND.h file

#include "AND.h"

bool AND::output(bool A, bool B){
    if (A && B == true){
        Out = true;
    } else {
        Out = false;
    }

    return Out;
}

Out in this case is an inherited variable.

有帮助吗?

解决方案 2

You're providing two definitions of AND::output. One in the header, which is empty, and another in the implementation file, which is not empty. Looks like your header should have:

bool output(bool A, bool B);

Note that you will not be able to use these output functions polymorphically because they do not have the same arguments as the declaration in Gate.

其他提示

You are defining method AND::output in the AND class definition here:

bool output(bool A, bool B){} // this is a definition

and you are re-defining it here:

bool AND::output(bool A, bool B){

  if (A && B == true){
  ....

You can fix this by changing the former to a declaration:

bool output(bool A, bool B);

As it was already said you defined function output twice: in the header and in the cpp module. Also this function is not virtual because its number and types of parameters do not coinside with the declaration of the virtual function with the same name in the base class.

I would like to append that the function could be defined much simpler

bool AND::output(bool A, bool B)
{
   return ( Out = A && B );
} 
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top