If i have file cSpeedOfSound.h:
#ifndef cSpeedOfSound_h
#define cSpeedOfSound_h
#include "Arduino.h"
#include "math.h"
class cSpeedOfSound{
public:
cSpeedOfSound(float *i,float *C);
private:
float *C;
float *a;
float *i;
};
#endif
and file cSpeedOfSound.cpp:
#include "cSpeedOfSound.h"
cSpeedOfSound::cSpeedOfSound(float *i,float *C){
//some code...
*C =roundto(*C,2);}
float cSpeedOfSound::roundto(float x,float dp){
return (round(x*pow(10., dp)) / pow(10., dp));}
where i want to run function roundto inside class, but it doesnt seems to work. So what im making wrong and how to do it properly?
Ps: Im begginer to arduino (want it to learn robotics + C language) and know python (learnd for about 1+ year), so pls do not hate me if i made crucial mistakes.
1 Answer 1
You need to include roundto()
in your class declaration, e.g. something like this:
class cSpeedOfSound {
public:
cSpeedOfSound(float *i,float *C);
private:
float roundto(float x, float dp);
float *C;
float *a;
float *i;
};
In C++, class structures are fixed. You can define the body of a function almost anywhere, but all member functions/data must be specified in the original declaration.
As a side note, it's worth pointing out that you have a naming conflict in your code. You have member variables called i
and C
, and you have totally separate function parameters called i
and C
. The compiler won't complain about this (the function parameters will simply mask the member variables), but it may not do what you expect.
roundto()
as a plain function. Declare it asstatic
to make it visible only from inside cSpeedOfSound.cpp. That's the C way of encapsulation.