重新定义类函数错误C++

Redefinition of class function error C++

本文关键字:类函数 错误 C++ 定义 新定义      更新时间:2023-10-16

我有我的基类Gate,而派生的类是AND(XOR等)。 我在基类中的虚拟函数用于确定输出,但是当我在 AND.h 中对其进行原型并尝试使用 AND 实现它时.cpp我在编译时收到重新定义错误。 我相信我已经正确地包含了所有内容。

门头

#ifndef GATE_H
#define GATE_H
class Gate{
    public:
        // various functions etc.
        virtual bool output();   // **PROBLEM FUNCTION**
};
#endif

门源

#include "Gate.h"
//*various function declarations but not virtual declaration*

派生类"AND"

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

以及我的 IDE 将我的错误放在 AND.h 文件中的位置

#include "AND.h"
bool AND::output(bool A, bool B){
    if (A && B == true){
        Out = true;
    } else {
        Out = false;
    }
    return Out;
}

在本例中为 Out 是一个继承变量。

您在此处定义AND类定义中的方法AND::output

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

你在这里重新定义它:

bool AND::output(bool A, bool B){
  if (A && B == true){
  ....

您可以通过将前者更改为声明来解决此问题:

bool output(bool A, bool B);

您提供了AND::output的两个定义。一个在标头中,为空,另一个在实现文件中,不为空。看起来您的标头应该具有:

bool output(bool A, bool B);

请注意,您将无法多态地使用这些output函数,因为它们与 Gate 中的声明没有相同的参数。

如前所述,您定义了两次函数输出:在标头和 cpp 模块中。此外,此函数不是虚拟函数,因为它的参数数量和类型与基类中具有相同名称的虚函数的声明不符。

我想补充一下,函数的定义可以简单得多

bool AND::output(bool A, bool B)
{
   return ( Out = A && B );
}