D
D
Detcelfer2018-12-18 04:39:19
Arduino
Detcelfer, 2018-12-18 04:39:19

How to correctly declare a function that uses a variable from a class, and a class that includes the use of this function?

I'll give an example:

//объявление функции
void someUniversalTool() {
  int variable1 = someClass.variableInClass ;
  //some additional code
}
//объявление класса
class someClass {
public:
  void someClassTool() {
    someUniversalTool();
    //some additional code
  }
  int variableInClass = 5;

} Someclass someclass;

In this case, there will be an error during compilation: 'someclass' was not declared in this scope;
If you swap function and class declarations, you will get an error: 'someUniversalTool()' was not declared in this scope;
How to declare them in a way that avoids such errors?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2018-12-18
@detcelfer

How to declare them in a way that avoids such errors?

A very strange construction in the code:
- if this is such a univeralTool, then why is it tied to the field of some specific object of some class?
- if you really need to get involved in the field of the object, then why is this function not a member of this class?
- if you need to process some value, then why not pass this value as a function argument?
Well, if it’s neither this nor that, and it’s really necessary as it is written in the code, then divide everything into parts and use declarations or order function definitions as it should, for example like this:
class someClass {
public:
  void someClassTool();
  int variableInClass = 5;
};

Someclass someclass;

void someUniversalTool()
{
  int variable1 = someClass.variableInClass ;
  //some additional code
}

void SomeClass::someClassTool()
{
   someUniversalTool();
   //some additional code
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question