简体   繁体   English

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

[英]Redefinition of class function error C++

I have my base class Gate, whilst the derived class is AND (XOR etc.). 我有基类Gate,而派生类是AND(XOR等)。 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. 我在基类中具有的虚函数用于确定输出,但是当我在AND.h中对它进行原型设计并尝试使用AND.cpp实现它时,在编译时会出现重新定义错误。 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" 派生类“ 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 以及我的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 in this case is an inherited variable. 在这种情况下,是一个继承的变量。

You are defining method AND::output in the AND class definition here: 您在此处的AND类定义中定义方法AND::output

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);

You're providing two definitions of AND::output . 您将提供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 . 请注意,您将无法多态使用这些output函数,因为它们与Gate的声明没有相同的参数。

As it was already said you defined function output twice: in the header and in the cpp module. 如前所述,您两次定义了函数输出:在标头和cpp模块中。 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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM