Any rookie question, so as not to clutter up the forum. Professionals, don't pass by. Nowhere without you - 6. - page 634

 
Hobu:

Here

https://docs.mql4.com/ru/basis/operators/return

it says:

"You can return simple types, simple structures, and pointers to objects . Thereturn operator cannot return any arrays, class objects, or variables of complex structure types.

"

Does this look like what is needed?

Russian identifiers are used, so it looks a bit unusual:

#property strict

/******************************************************************************/
struct ОфигеннаяСтруктура {
private:
  int значение;

public:
  ОфигеннаяСтруктура(int значение = 0): значение(значение) { }
  int выдатьЗначение() const { return значение; }
};

/******************************************************************************/
ОфигеннаяСтруктура Функа(int значение) {
  ОфигеннаяСтруктура местная(значение);

  return местная; // Возвращаем структуру из функции
}

/******************************************************************************/
void OnStart() {
  Print("Начинаем безобразничать...");

  ОфигеннаяСтруктура штукаРаз = Функа(5);

  Print("Значение штукиРаз = ", штукаРаз.выдатьЗначение());

  ОфигеннаяСтруктура штукаДва;

  Print("Значение штукиДва первое = ", штукаДва.выдатьЗначение());
  штукаДва = Функа(7);
  Print("Значение штукиДва второе = ", штукаДва.выдатьЗначение());

  Print("Заканчиваем безобразничать...");
}

The result of running this is as follows:

23:55:39 Script 1 EURUSDm,H1: loaded successfully
23:55:39 1 EURUSDm,H1: initialized
23:55:39 1 EURUSDm,H1: Начинаем безобразничать...
23:55:39 1 EURUSDm,H1: Значение штукиРаз = 5
23:55:39 1 EURUSDm,H1: Значение штукиДва первое = 0
23:55:39 1 EURUSDm,H1: Значение штукиДва второе = 7
23:55:39 1 EURUSDm,H1: Заканчиваем безобразничать...
23:55:39 1 EURUSDm,H1: uninit reason 0
23:55:39 Script 1 EURUSDm,H1: removed
The thingRaz object is initialized with the object (structure) returned from the Funk function, and the thingTwo object is initialized with the default value, but then an object (structure) is assigned to it, also returned from the Funk function.
 
simpleton:

Does this look like the right thing to do?

Russian identifiers have been used, so it looks a bit unusual:

The result of running this is as follows:

The thingRaz object is initialized with the object (structure) returned from the Funk function, and the thingTwo object is initialized with the default value, but then an object (structure), also returned from the Funk function, is assigned to it.

 

Please, can you comment in detail on the way that simpleton described, every line including syntax? I don't understand what it means yet. Not necessarily on the fingers, you can also use terms, but line by line.

1)So, does Funk's function return an object and not some mediocre value, like other mediocre functions do? What kind of beast is this, why is it an object?

2)Can we initialize with either an object returned from the function or a default value? That is, the Funk function, although it is part of the same structure, has nothing to do with the object Thing 2, or am I misunderstanding something? By the way, it is called an object, so the structure has an object, too? I thought it was simpler than that. And another question, how exactly do I copy one structure to another, if they are of the same type? This simple line.

ОфигеннаяСтруктура штукаДва;

and there is a notorious copying? And there's no need to declare the structure of Stuka 2 separately, and it's not a structure at all, but an object created by a structure?

I'm somehow not familiar with any programming languages (but not against learning) and moreover, have a rather vague idea of OOP, so don't be surprised if the questions are stupid.

Oops, I have just seen that the braces are closed before, i.e. this Funka is described outside the structure, but what exactly is it in relation to the structure Awesome?

 
Hobu:

Please, can you comment in detail on the way that simpleton described, every line including syntax? I don't understand what it means yet. Not necessarily on the fingers, you can also use terms, but line by line.

1)So, does Funk's function return an object and not some mediocre value, like other mediocre functions do? What kind of beast is this, why is it an object?

2)Can we initialize with either an object returned from the function or a default value? That is, the Funk function, although it is part of the same structure, has nothing to do with the object Thing 2, or am I misunderstanding something? By the way, it is called an object, so the structure has an object, too? I thought it was simpler than that. And another question, how exactly one structure can be copied into another one, if they are of the same type? This simple line.

And there is the notorious copying? And you don't have to declare the type 2 structure separately and it's not a structure at all, but an object created by a structure?

I'm somehow not familiar with any programming language at all (but not against learning) and moreover have rather vague idea about OOP, so don't be surprised if questions are stupid.

Oops, I just saw that the braces are closed before, i.e. this function is described outside the structure, but what exactly is it in relation to the structure Awesome?

Something like this, compared to the same thing, but for a variable of one of the built-in types:
#property strict

/******************************************************************************/
struct ОфигеннаяСтруктура { // Заводим структуру
private: // Просто так извне к следующим элементам нельзя обратиться
  int значение; // Поле данных для хранения в структуре

public: // К следующим элементам можно просто так обратиться извне
  ОфигеннаяСтруктура(int значение = 0): значение(значение) { } // Конструктор: инициализирует поле значением переданного параметра; если параметр не передан, используется значение по умолчанию, равное 0
  int выдатьЗначение() const { return значение; } // Метод: возвращает значение поля, может вызываться для структур, переменные для которых объявленных как константные
};

/******************************************************************************/
ОфигеннаяСтруктура Функа1(int значение) { // Функция, возвращающая структуру
  ОфигеннаяСтруктура местная(значение); // Создание локальной переменной, в данном случае, судя по типу, это - структура

  // Если структура посложнее, чем в этом примере, то тут можно выполнить над ней какие-то дополнительные действия

  return местная; // Возвращаем структуру из функции
}

/******************************************************************************/
string Функа2(int значение) { // Функция, возвращающая один из встроенных типов
  string Таблица[] = {"Ноль", "Один", "Два"};

  /* Никакого особого смысла тут нет, просто имитация деятельности */
  return Таблица[значение % 3]; // Возвращаем строку из функции (остаток от деления параметра на три словами)
}

/******************************************************************************/
void OnStart() {
  Print("Начинаем безобразничать...");

  ОфигеннаяСтруктура штукаРаз = Функа1(5); // Заводим переменную (структуру) с одновременной инициализацией
  string строкаРаз = Функа2(5); // Заводим переменную (один из встроенных типов) также с инициализацией

  Print("Значение штукиРаз = ", штукаРаз.выдатьЗначение()); // Для получения значения поля структуры вызывается специально под это написанный метод
  Print("Значение строкиРаз = ", строкаРаз);

  ОфигеннаяСтруктура штукаДва; // Заводим переменную (структуру) без явной инициализации (конструктор получает в качестве значения параметра значение, указанное по умолчанию, и структура инициализируется им)
  string строкаДва; // Заводим переменную (один из встроенных типов) без инициализации (переменные типа string, объявленные таким образом, инициализируются пустой строкой)

  Print("Значение штукиДва первое = ", штукаДва.выдатьЗначение());
  Print("Значение строкиРаз первое = '", строкаРаз, "'");

  штукаДва = Функа1(7); // Присвоение переменной штукаДва типа структура значения типа структура, возвращённого функцией Функа1
  строкаДва = Функа2(7); // Присвоение переменной строкаДва одного из встроенных типов (строка) значения того же типа, возвращённого функцией Функа2

  Print("Значение штукиДва второе = ", штукаДва.выдатьЗначение());
  Print("Значение строкиРаз второе = '", строкаРаз, "'");

  Print("Заканчиваем безобразничать...");
}

The result of the run is as follows:

21:16:29 Script 1 EURUSDm,H1: loaded successfully
21:16:29 1 EURUSDm,H1: initialized
21:16:29 1 EURUSDm,H1: Начинаем безобразничать...
21:16:29 1 EURUSDm,H1: Значение штукиРаз = 5
21:16:29 1 EURUSDm,H1: Значение строкиРаз = Два
21:16:29 1 EURUSDm,H1: Значение штукиДва первое = 0
21:16:29 1 EURUSDm,H1: Значение строкиРаз первое = ''
21:16:29 1 EURUSDm,H1: Значение штукиДва второе = 7
21:16:29 1 EURUSDm,H1: Значение строкиРаз второе = 'Один'
21:16:29 1 EURUSDm,H1: Заканчиваем безобразничать...
21:16:29 1 EURUSDm,H1: uninit reason 0
21:16:29 Script 1 EURUSDm,H1: removed

Functions return objects of the type specified in the declaration. By objects here we mean not only structures, but built-in types as well.

If the type of the returned value for the Funk1 function is of the OffigenStructure type, which is a structure, it means that this function returns the values of the structures, and only of the OffigenStructure type. It does this because and only because its declaration/definition has this return type.

You may initialize it with such value or values, just like one of the constructors takes. You can do without constructors, but their initialization syntax is a bit different and they have their own limitations.

In this case, the constructor takes a value of int type, so a variable of OxygenStructure type should be initialized with a value of int type, or another type, but implicitly cast to int.

Since the default value is specified for the parameter that the constructor accepts, you don't have to pass a value to the constructor. The constructor will be called anyway, but the default parameter will be used.

That uncomplicated string is just a declaration for a variable of typeSteamStructure. Copying structures of the same type into each other is extremely easy, just like "copying" the values of a built-in type variable. You need to assign a value from one variable to the other. For example, "thingRaz = thingTwo;". Execute it yourself and print out the value that the variable shtuRaz has become after this assignment.

Funk1 has nothing to do with structures of typeOfgenericStructure except that it returns values of that type.

You need general training, you'll "drown" without it. I'm not ready to give you advice.

I can give you the following advice briefly from what I can see (the basics):

1. Data in a program is stored in named areas of memory, called variables.

2. the type of variable defines a way of interpretation of the stored data and, in the vast majority of cases, its size. The way of interpretation implies a set of operations that can be performed on the data.

3. Embedded and structured types are not conceptually different from this point of view.

Point 2 is the most important and fundamental to understand. In C++ and MQL, the notion of type is very important.

In a nutshell: a type is a "pattern" of data, and a variable is a unit of that pattern. A cat or a doggie is a "pattern", and specific cats like Murzyk or dogs like Sharik are units of cats and dogs. It's the same with types and variables.

 
Hobu:

Please, can you comment in detail on the way that simpleton described, every line including syntax? I don't understand what it means yet. Not necessarily on the fingers, you can also use terms, but line by line.

1)So, does Funk's function return an object and not some mediocre value, like other mediocre functions do? What kind of beast is this, why is it an object?

2)Can we initialize with either an object returned from the function or a default value? That is, the Funk function, although it is part of the same structure, has nothing to do with the object Thing 2, or am I misunderstanding something? By the way, it is called an object, so the structure has an object, too? I thought it was simpler than that. And another question, how exactly do I copy one structure to another, if they are of the same type? This simple line.

and there is a notorious copying? And there's no need to declare the structure of Stuka 2 separately, and it's not a structure at all, but an object created by a structure?

I'm somehow not familiar with any programming languages (but not against learning) and moreover, have a rather vague idea of OOP, so don't be surprised if the questions are stupid.

Oops, I just saw that the braces are closed before, i.e. this Funka is described outside the structure, but what exactly is it in relation to the structure Awesome?


Tartu? Youoohoo...
 

Old guys, tell me how to calculate the number of filled cells in a two-dimensional array.

 for(int i=0;i<ObjectsTotal();i++) 
{
  mas[0][i]-количество заполненных ячеек?
  mas[1][i]-//-//-//-//-//-//-//-//-//-
}
 

Please help me with the code to display just one figure on the chart - the level of loss, if not difficult.

Here it is in this extension good https://www.mql5.com/ru/code/8873 it is and so it is called the level of plum, it is displayed in red, although also the level of margin is a normal topic but at least that one to start with, otherwise, the extension is cool but there are many things that I do not need, and I can not understand how it is obtained there.

 
Top2n:

Old guys, tell me how to calculate the number of filled cells in a two-dimensional array.


ArrayRange
 
r772ra:

ArrayRange


This function returns the number of cells in the array, not the number of filled cells.

Can anyone tell me how to do one-dimensional?))

 
Top2n:

This function returns the number of cells in the array, not the number of filled cells.

Only a loop will help you. Go through and count