开发者

multiple declaration error- virtual functions

开发者 https://www.devze.com 2023-02-03 09:55 出处:网络
I have observer.h ,client.h and field.h files. In observer.h there is Subject class which has // observer.h

I have observer.h , client.h and field.h files.

In observer.h there is Subject class which has

// observer.h

class Subject  {
public:
 virtual ~Sub开发者_开发知识库ject(){};
 Subject(){};
 virtual void Attach(Observer*);
 virtual void Detach(Observer*);
 virtual void Notify(bool _value);
 virtual bool getCheckedIn(){};
private:
 vector < Observer* >  _observers;
};

 

#ifndef CLIENT_H
#define CLIENT_H

#include "Field.h"

class Client : public Subject {
public:
 Client(string _name, Field *_field) : client_name(_name) ,field(_field) , checked_in(false) {}

 void setCheckedIn(bool _value){
  checked_in = _value;
  Notify(_value);
 }

 void enterRow(string _row_name){
  field->deneme();
  setCheckedIn(true);
 }

 bool getCheckedIn(){ return checked_in;}
private:
 bool checked_in;
 string client_name;

 Field *field;

};

#endif // CLIENT_H

 

#ifndef Field_H
#define Field_H
#include "CreateRow_absFac.h"
#include "observer_pattern.h"
#include <vector>
#include <string>
using namespace std;

// Template Class 
class Field{
public:
 Field(); 
 // Template method 
 void field_creator();
 virtual void setAbstractRow() = 0;
protected:
 FarmFactory *abstract_row1;
 FarmFactory *abstract_row2;
 FarmFactory *abstract_row3;

 Rows *row1 ;
 Rows *row2 ;
 Rows *row3 ;
 Sensor sensor1; 
};

When compiled , got this error :

ld: duplicate symbol Subject::Notify(bool) in /Users/barisatamer/Desktop/se311/PROJECT/build/PROJECT.build/Debug/PROJECT.build/Objects-normal/x86_64/Field.o and /Users/barisatamer/Desktop/se311/PROJECT/build/PROJECT.build/Debug/PROJECT.build/Objects-normal/x86_64/main.o

If I remove virtual functions it compiles without error. What is the problem with virtual functions ?


We can't actually see it here, but the problem is probably that you defined Subject::notify(bool) in a header file (your observer.h just declares it, it doesn't define it) and you included that header file in both Field.cpp and main.cpp, so you get multiple definitions. The fix is to move the definition into a source file so its only defined once.

General rule -- DECLARE things in header files, DEFINE them in non-header source files. Note that include guards are irrelevant here -- they prevent something being declared multiple times in a single compilation unit, but what's needed is to avoid defining something multiple times in different compilation units.


Try keeping header guards even for your observer.h. BTW, Why aren't you overriding virtual functions in the derived class ?


Apparently you have an ODR violation. Why did you get away with non-virtual functions? Possibly because you defined them inline (e.g. in class). As it was suggested, check the include guards and function definitions.

0

精彩评论

暂无评论...
验证码 换一张
取 消