Function and Class errors - c++

class BufferFile{
public:
BufferFile(IOBuffer &);
int Open(char *);
int Create(char *);
int Close();
int Rewind();
int Read(int recaddr = -1);
int Write(int recaddr = -1);
int Append();
IOBuffer & GetBuffer();
protected:
IOBuffer & Buffer;
std::fstream File;
int HeaderSize;
int ReadHeader();
int WriteHeader();
};
BufferFile::BufferFile(IOBuffer & from):Buffer(from){}
int BufferFile::Read(int recaddr){
if(recaddr==1) return Buffer.Write(File);
else return Buffer.DWrite(File, recaddr);
}
int BufferFile::Append(){
File.seekp(0,std::ios::end);
return Buffer.Write(File);
}
IOBuffer & BufferFile::GetBuffer(){
return Buffer;
}
int BufferFile::ReadHeader(){
return Buffer.ReadHeader(File);
}
int BufferFile::WriteHeader(){
return Buffer.WriteHeader(File);
}
I am getting several errors form the IOBuffer field, saying that it was not declared in the function scopes or "expected `)' before ‘&’ token" on the constructor, what is causing these?
Here are all the files involved in this project:
Person.h!
Buffile.cpp
BuffFile.h
Delim.cpp
Delim.h
Fixfld.cpp
Fixfld.h
FixLen.cpp
FixLen.h
Iobuffer.cpp
Iobuffer.h
Length.cpp
Length.h
Varlen.cpp
Varlen.h

I think your problem is this (from Buffile.h):
#ifndef IOBUFFER
#define IOBUFFER
#include "Iobuffer.h"
#endif
... that logic breaks the similar/redundant logic that you have in Iobuffer.h:
#ifndef IOBUFFER
#define IOBUFFER
class IOBuffer{
[...]
#endif
The problem is that the declaration of "class IOBuffer" in Iobuffer.h is never parsed, because the compiler value IOBUFFER was already defined inside Buffile.h, and thus the #ifndef IOBUFFER at the top of Iobuffer.h is not activated.
The right way to do it is to modify Buffile.h to include only the #include "Iobuffer.h" line, and leave it up to the contents of Iobuffer.h to do the #ifndef and #define stuff.

Related

Why is my c++ singleton not working on Clion?

I want to have a singleton in my project but some errors occur
this is my codes in three separate files.:
//---------------My main.cpp code
#include <iostream>
#include "Sports/BBVB.h"
int main() {
bbvb;
return 0;
}
// ---------------------------my BBVB.h code
#ifndef SAMAVAR_BBVB_H
#define SAMAVAR_BBVB_H
typedef struct VBResult{
int set1=-1;
int set2=-1;
int set3=-1;
int set4=-1;
int set5=-1;
}VBResult;
#include "Sport.h"
#include "../TournamentStuf/Tournament.h"
class BBVB: public Sport {
protected:
vector<Tournament<VBResult>> tours;
public:
static BBVB& getInstance(){
static BBVB b;
return b;
}
private:
BBVB(){}
public:
BBVB(BBVB const&)=delete;
void operator=(BBVB const&) = delete;
//-------------Setter------------
//------------Getter-------------
vector<Tournament<VBResult>> getTours() const;
Tournament<VBResult> getTourById(int id) const;
//----------Others---------------
void addTour(Tournament<VBResult> v);
};
BBVB &bbvb=BBVB::getInstance();
#endif //SAMAVAR_BBVB_H
//------------------my Store and restore code
#ifndef SAMAVAR_STOREANDRESTORE_H
#define SAMAVAR_STOREANDRESTORE_H
#include "../Sports/BBVB.h"
#include "../Sports/PingPong.h"
#include "../Sports/Wrestling.h"
void Start(BBVB &b);
void Update(const BBVB &b);
void Start(PingPong &p);
void Update(const PingPong &p);
void Start(Wrestling &w);
void Update(const Wrestling &w);
#endif //SAMAVAR_STOREANDRESTORE_H
I have a bbvb instance of BBVB but it says you have multiple definitions of it.
I'm new to Clion and I don't have enough information about somethings like cmake and I feel the problem is because of it.
I want to have something like cout and cin in iostream.so by including my BBVB I can access this object.
Clion shows error below:
CMakeFiles\Samavar.dir/objects.a(BBVB.cpp.obj):BBVB.cpp:(.bss+0x0): multiple definition of `bbvb'
CMakeFiles\Samavar.dir/objects.a(main.cpp.obj):main.cpp:(.bss+0x0): first defined here
CMakeFiles\Samavar.dir/objects.a(StoreAndRestore.cpp.obj):StoreAndRestore.cpp:(.bss+0x0): multiple definition of `bbvb'
CMakeFiles\Samavar.dir/objects.a(main.cpp.obj):Samavar-master/Sports/BBVB.h:24: first defined here
collect2.exe: error: ld returned 1 exit status

redefinition of classes error in c++

I searched through some of the other pages with this same error, but my code does not have any of their issues that I can find.
I have a base class named QBase defined in quadrature.h:
#ifndef SRC_QUADRATURE_H_
#define SRC_QUADRATURE_H_
#include "enum_order.h"
#include "enum_quadrature_type.h"
#include <vector>
#include <memory>
class QBase
{
protected:
QBase (const Order _order=INVALID_ORDER);
public:
virtual ~QBase() {}
virtual QuadratureType type() const = 0;
static std::unique_ptr<QBase> build (const QuadratureType qt, const Order order=INVALID_ORDER);
const std::vector<double> & get_points() const { return _points; }
const std::vector<double> & get_weights() const { return _weights; }
std::vector<double> & get_points() { return _points; }
std::vector<double> & get_weights() { return _weights; }
protected:
const Order _order;
std::vector<double> _points;
std::vector<double> _weights;
};
#endif /* SRC_QUADRATURE_H */
I derive a class QGaussLegendre by QBase definded in gauss_legendre.h
#ifndef SRC_QUADRATURE_GAUSSLEGENDRE_H_
#define SRC_QUADRATURE_GAUSSLEGENDRE_H_
#include "quadrature.h"
class QGaussLegendre : public QBase
{
public:
QGaussLegendre (const Order _order=INVALID_ORDER) : QBase (_order){}
~QGaussLegendre (){}
virtual QuadratureType type() { return QGAUSSLEGENDRE; }
};
#endif /* SRC_QUADRATURE_GAUSSLEGENDRE_H_ */
In the main file I use the build() member function to get points and weights as follows
const Order order = ddp.order;
const QuadratureType qt = ddp.qt;
static std::unique_ptr<QBase> qr(QBase::build(qt,order));
const std::vector<double>& points = qr->get_points();
const std::vector<double>& weights = qr->get_weights();
I don't have any problem till here. Now, the points and weights are defined in the file legendre_gauss.cxx
#include "gauss_legendre.h"
QGaussLegendre::QGaussLegendre(const Order order)
{
switch(order)
{
case CONSTANT:
case FIRST:
{
_points.resize (1);
_weights.resize(1);
_points[0](0) = 0.;
_weights[0]= 2.;
}
}
}
When I compile this last file I get the error:
/home/matteo/flux/gauss_legendre.cxx:13:1:
error: redefinition of ‘QGaussLegendre::QGaussLegendre(qenum::Order)’
QGaussLegendre::QGaussLegendre(const Order order)
^~~~~~~~~~~~~~
In file included from /home/matteo/flux/gauss_legendre.cxx:8:0:
/home/matteo/flux/gauss_legendre.h:25:3:
note: ‘QGaussLegendre::QGaussLegendre(qenum::Order)’ previously
defined here
QGaussLegendre (const Order _order=INVALID_ORDER) : QBase (_order)
^~~~~~~~~~~~~~
Can I do to solve the problem? Thanks a lot.
redefinition of classes error
That's not an error about redefinition of a class. That is an error about redefinition of a function. In particular, redefinition of the function QGaussLegendre::QGaussLegendre(const Order order) which is the contsructor of class QGaussLegendre.
You've defined it first here in quadrature.h:
QGaussLegendre (const Order _order=INVALID_ORDER) : QBase (_order){}
And second time in legendre_gauss.cxx:
QGaussLegendre::QGaussLegendre(const Order order)
{
Can I do to solve the problem?
Solution is to define the function exactly once.

Arduino: pass function to class, returning String

I'm trying to get my Arduino class to return String messages with all kind of information for logging. With lots of trial and error I manage to pass a reference to the logging function to the class, but can only get a char* but not a String, and I want to be able to send Strings making it so much easier to send back all kinds of data.
I have the first part working already.
The sketch:
#include <Test.h>
#include <string.h>
void setup() {
Serial.begin(115200);
Test t;
t.setLogging(writeLog);
writeLog("Test message!" + String(" .... "));
t.doSomething("This is useful.");
t.doSomething("This as well.\n");
t.doSomething("This is even more useful.\n");
bool b = true;
}
void loop() {
}
void writeLog (char* message) {
Serial.print("char function: ");
Serial.print(message);
}
void writeLog (String message) {
Serial.print("String function: ");
Serial.println(message);
}
The header file:
#ifndef TEST_h
#define TEST_h
class Test
{
public:
Test(); // The constructor.
void setLogging(void (*)(char*)); // Takes function setting where to log.
void doSomething(char*);
};
#endif
The class:
#include <Test.h>
typedef void (*LogFunction)(char*);
LogFunction writeLog;
Test::Test () {
}
void Test::doSomething (char* s) {
// Do something useful and log the result.
writeLog(s);
}
void Test::setLogging (void (*f)(char*) ) {
writeLog = f;
return;
}
Now what I want my class to be able to do is send information like this, as String, rather than char* (I also haven't found an easy way of converting "anything" to char* and then concatenating the two or more strings):
writeLog ("HydroMonitorECSensor::setCalibration Receiving calibration - haveCalibration = " + String(haveCalibration));
writeLog ("HydroMonitorECSensor::setCalibration calibratedSlope = " + String(calibratedSlope));
writeLog ("HydroMonitorECSensor::setPins capPos set to " + String(capPos));
Where haveCalibration is a bool (which as String becomes either "true" or "false"), calibratedSlope is a double and capPos is an int. This way I can easily and cleanly send complete lines to the logger. Works great within the main script - not from the class.
I tried simply changing the char* to String and adding #include <string.h> to the library files but it doesn't work.
In Test.cpp I then get void Test::setLogging (void (*f)(String) ) { and in Test.h void setLogging(void (*)(String)); and now I get error messages:
In file included from /home/wouter/Arduino/libraries/Test/Test.cpp:1:0:
/home/wouter/Arduino/libraries/Test/Test.h:10:29: error: expected ',' or '...' before '(' token
void setLogging(void (*)(String)); // Takes function setting where to log.
^
/home/wouter/Arduino/libraries/Test/Test.cpp:16:40: error: variable or field 'setLogging' declared void
void Test::setLogging (void (*f)(String) ) {
^
/home/wouter/Arduino/libraries/Test/Test.cpp:16:31: error: 'f' was not declared in this scope
void Test::setLogging (void (*f)(String) ) {
^
/home/wouter/Arduino/libraries/Test/Test.cpp:16:34: error: 'String' was not declared in this scope
void Test::setLogging (void (*f)(String) ) {
^
exit status 1
Error compiling for board NodeMCU 1.0 (ESP-12E Module).
Suggestions?
Additional info, maybe important: I'm using the Arduino IDE and compile for ESP8266.
You are using the Arduino-provided String class, but didn't include the Arduino.h header in your test.h header file. That causes it to not find the String class and compilation fails.
The following works:
main.cpp:
#include <Arduino.h>
#include <test.hpp>
void writeLog (char* message);
void writeLog (String message);
void setup() {
Serial.begin(115200);
Test t;
t.setLogging(writeLog);
writeLog("Test message!" + String(" .... "));
t.doSomething("This is useful.");
t.doSomething("This as well.\n");
t.doSomething("This is even more useful.\n");
bool b = true;
}
void loop() {
}
void writeLog (char* message) {
Serial.print("char function: ");
Serial.print(message);
}
void writeLog (String message) {
Serial.print("String function: ");
Serial.println(message);
}
test.hpp:
#ifndef TEST_h
#define TEST_h
#include <Arduino.h> //for "String" class
//Typdef for the log function. Takes a String, returns nothing
typedef void (*LogFunction)(String);
class Test
{
public:
Test(); // The constructor.
// void setLogging(void (*)(char*)); // Takes function setting where to log.
void setLogging(LogFunction); //use the typedef here
void doSomething(char*);
};
#endif
test.cpp:
#include <test.hpp>
LogFunction writeLog;
Test::Test () {
}
void Test::doSomething (char* s) {
// Do something useful and log the result.
writeLog(s);
}
//void Test::setLogging (void (*f)(char*) ) {
void Test::setLogging (LogFunction f) { //also use typedef here
writeLog = f;
return;
}
Among other things that may arise, the compiler tells you that it cannot resolve identifier String.
This can have several reasons: First, you write String, and not string (note the capital letter in your writing). Second, if you write string and not std::string, it cannot be resolved unless you have either declared using namespace std (which is not the preferred variant for several reasons) or using std::string. Third, class std::string is declared in header <string>, which is something different than <string.h>.
So I'd write #include <string> and use then std::string.

Arduino C++ file - class instantiation fails when setting a private member variable in the constructor

I'm using the Arduino IDE 1.0.5-r2 and trying to create a class with two member variables, _pinA and _pinB. When I call the constructor from my Arduino sketch, I get this error:
RotaryEncoderReader.cpp:6: error: request for member '_pinB' in 'this', which is of non-class type 'RotaryEncoderReader* const'
The constructor can be called from a regular C++ files compiled using GCC, and there are no errors. Am I missing something about how to use a class constructor with an Arduino?
Here is the class header:
#ifndef RotaryEncoderReader_h
#define RotaryEncoderReader_h
#include "Arduino.h"
class RotaryEncoderReader {
private:
int _pinA;
int _pinB;
volatile long encoderPos;
public:
RotaryEncoderReader( int newPinA, int newPinB );
void doEncoderA();
void doEncoderB();
long getPosition();
};
#endif
Here's the implementation:
#include "RotaryEncoderReader.h"
RotaryEncoderReader::RotaryEncoderReader( int newPinA, int newPinB )
: _pinA(newPinA),
_pinB(newPinB),
encoderPos(0)
{
}
void RotaryEncoderReader::doEncoderA()
{
//Irrelevant
}
void RotaryEncoderReader::doEncoderB()
{
//Irrelevant
}
long RotaryEncoderReader::getPosition()
{
return _pinA + _pinB;
}
And here's the Arduino sketch:
#include <RotaryEncoderReader.h>
int pinA = 2;
int pinB = 3;
RotaryEncoderReader reader(pinA, pinB);
void setup()
{
}
void loop()
{
}

C++ Class Methods Declaration Returns Error

I have recently started working with C++ classes and had just started when I reached an error. I have a "resource.h" file that contains the class definition of two classes: 'deck' and 'card'. I #included this file in another file, "card.cpp". In the card.cpp file I described all the methods/functions of the 'card' class. However on compilation I am getting the following the errors (fyi I am using the MinGW compiler for command-line):
card.cpp:3:29: error: ISO C++ forbids declaration of 'setCard' with no
type [-fp ermissive] card.cpp:3:1: error: prototype for 'int
Card::setCard(char, char)' does not matc h any in class 'Card'
resource.h:9:8: error: candidate is: void Card::setCard(char, char)
The "card.cpp" file:
#include "resource.h"
Card::setCard(char f, char s) {
face = f;
suit = s;
}
Card::Card (char face, char suit) {
setCard(face, suit);
}
Card::~Card () {}
The "resource.h" file:
typedef unsigned short int UINT;
class Card;
class Deck;
class Card {
public:
Card(char face, char suit);
~Card();
void setCard(char face, char suit);
char getFace() const { return face; }
char getSuit() const { return suit; }
private:
char face;
char suit;
};
class Deck {
public:
Deck();
~Deck();
Card getCard(UINT x);
private:
Card myCards[54];
};
What is causing this issue, and why in the world does the compiler think that "Card::setChard()" is an int
Card::setCard(char f, char s) {
face = f;
suit = s;
}
should be
void Card::setCard(char f, char s) {
face = f;
suit = s;
}
Some hints that helped me get to this amazing conclusion:
C++ forbids declaration of 'setCard' with no type
candidate is: void Card::setCard(char, char)
If you thought this was cryptic, hold on tight for when you get to templates. Compilers have a history of generating great error messages for them.