Recent

Author Topic: External: SIGSEGV  (Read 9369 times)

Zeno

  • Newbie
  • Posts: 6
External: SIGSEGV
« on: December 22, 2021, 03:00:09 am »
Добрый день!
Помогите разобраться. Почему данный простой код не работает как положено.

Code: Pascal  [Select][+][-]
  1. unit Unit1;
  2.  
  3. {$mode objfpc}{$H+}
  4.  
  5. interface
  6.  
  7. uses
  8.   Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls;
  9.  
  10. type
  11.  
  12.   { TForm1 }
  13.  
  14.   TForm1 = class(TForm)
  15.     Button1: TButton;
  16.     Label1: TLabel;
  17.     procedure Button1Click(Sender: TObject);
  18.   private
  19.  
  20.   public
  21.  
  22.   end;
  23.   Number = Class
  24.     nb: double;
  25.   end;
  26.  
  27. var
  28.   Form1: TForm1;
  29.  
  30. implementation
  31.  
  32. {$R *.lfm}
  33.  
  34. { TForm1 }
  35.  
  36. procedure TForm1.Button1Click(Sender: TObject);
  37. var
  38.   N1: Number;
  39. begin
  40. N1.nb:= (120.341154260366);
  41. label1.caption:= floattostr(N1.nb);
  42. end;
  43.  
  44. end.
  45.          
Если сделать nb обычной глобальной переменной то код работает. А если сделать nb переменной  класса - не работает. Объясните, пожалуйста, почему и покажите как нужно делать, так чтобы все работало. Я новичок, только изучаю ООП.

Спасибо!

Handoko

  • Hero Member
  • *****
  • Posts: 5122
  • My goal: build my own game engine using Lazarus
Re: External: SIGSEGV
« Reply #1 on: December 22, 2021, 03:52:14 am »
You did it wrong.

That should be like this:

Code: Pascal  [Select][+][-]
  1. unit Unit1;
  2.  
  3. {$mode objfpc}{$H+}
  4.  
  5. interface
  6.  
  7. uses
  8.   Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls;
  9.  
  10. type
  11.  
  12.   { TForm1 }
  13.  
  14.   TForm1 = class(TForm)
  15.     Button1: TButton;
  16.     Label1: TLabel;
  17.     procedure Button1Click(Sender: TObject);
  18.   private
  19.  
  20.   public
  21.  
  22.   end;
  23.  
  24.   { TNumber }
  25.  
  26.   TNumber = class
  27.   private
  28.     FNB: Double;
  29.   public
  30.     constructor Create;
  31.     property NB: Double read FNB write FNB;
  32.   end;
  33.  
  34. var
  35.   Form1: TForm1;
  36.  
  37. implementation
  38.  
  39. {$R *.lfm}
  40.  
  41. { TNumber }
  42.  
  43. constructor TNumber.Create;
  44. begin
  45.   FNB := 0;
  46. end;
  47.  
  48. { TForm1 }
  49.  
  50. procedure TForm1.Button1Click(Sender: TObject);
  51. var
  52.   N1: TNumber;
  53. begin
  54.   N1    := TNumber.Create;
  55.   N1.NB := 120.341154260366;
  56.   Label1.Caption := FloatToStr(N1.NB);
  57.   N1.Free
  58. end;
  59.  
  60. end.

  • Usually a class has a private section (see line #27) and a public section (see line #29), read more https://wiki.freepascal.org/Class#Scope_modifiers
  • Class name usually started with an uppercase letter T, so that class should be named TNumber (see line #26).
  • You put variables in the private section and the name usually started with an uppercase letter F, so that variable should be named FNB (see line #28).
  • In the point #2 above, the letter T means type and in the point #3, the letter F means field.
  • You set the default values inside a constructor, which usually named as Create (see lines #30, #43, #45).
  • To let users to access the value, you create a property (see line #31).
  • You must call the constructor before you can use the class (see line #54).
  • Usually you have to call Free if you no longer need it (see line #57), but there are some classes do not always require you to free them manually, for examples: TButton, TImage, etc.
« Last Edit: December 22, 2021, 11:29:13 am by Handoko »

WooBean

  • Full Member
  • ***
  • Posts: 229
Re: External: SIGSEGV
« Reply #2 on: December 22, 2021, 09:26:21 am »
@Zeno

Less typing solution:
change your Number class definition to
Quote
Number = Class
 class var nb: double;
end;

... and your code works OK.

However, a lot reading obout OOP instead of you.
Platforms: Win7/64, Linux Mint Ulyssa/64

Sieben

  • Sr. Member
  • ****
  • Posts: 310
Re: External: SIGSEGV
« Reply #3 on: December 22, 2021, 10:02:52 am »
Quote
8. Usually you have to call Free if you no longer need it (see line #57), but there are some classes do not require you to free them manually, for examples: TButton, TImage, etc.

Not quite. You don't need to explicitely free an instance when it's Create takes an Owner as parameter and this parameter is not nil, because then the Owner is responsible for freeing it. This is true eg for any component like a TButton or TImage being dropped on a form at design time, but if you have sth like

Code: Pascal  [Select][+][-]
  1.   MyButton := TButton.Create(nil);

in your code you will have to free MyButton manually as well. Sure you know that.
Lazarus 2.2.0, FPC 3.2.2, .deb install on Ubuntu Xenial 32 / Gtk2 / Unity7

Handoko

  • Hero Member
  • *****
  • Posts: 5122
  • My goal: build my own game engine using Lazarus
Re: External: SIGSEGV
« Reply #4 on: December 22, 2021, 11:24:36 am »
Please don't focus on me. Think about the OP, he's just an beginner. You all know, OOP cannot be explained using some paragraphs only. If you try to include class var, ownership, etc ... that only makes the OP harder to learn OOP.

Zeno

  • Newbie
  • Posts: 6
Re: External: SIGSEGV
« Reply #5 on: December 22, 2021, 08:13:53 pm »
У меня есть еще пара вопросов: Почему?
Code: Pascal  [Select][+][-]
  1. N1:= TNumber.Create; //работает правильно
  2. N1.Create; //работает с ошибкой
  3.  
Ведь синтаксический анализатор признает оба варианта правильными, разве это не одно и то же?
И второй вопрос: как создать массив типа TNumber? Нужно ли каждый элемент массива инициализировать конструктором или же можно выделить память для каждого элемента операцией New?

Handoko

  • Hero Member
  • *****
  • Posts: 5122
  • My goal: build my own game engine using Lazarus
Re: External: SIGSEGV
« Reply #6 on: December 23, 2021, 04:33:37 am »
I don't know and I don't care why the syntax analyzer accepts the line #10, there were no compile error, warning, nor hint. I just want to tell you, don't do it:

Code: Pascal  [Select][+][-]
  1. type
  2.   TNumber = class
  3.     // ...
  4.   end;
  5.  
  6. procedure TForm1.Button1Click(Sender: TObject);
  7. var
  8.   N1: TNumber;
  9. begin
  10.   N1.Create;
  11. end;

If you're interested, I started a new thread:
https://forum.lazarus.freepascal.org/index.php/topic,57612.msg428687.html#msg428687



Array of TNumber:

Code: Pascal  [Select][+][-]
  1. procedure TForm1.Button1Click(Sender: TObject);
  2. const
  3.   ItemCount = 10;
  4. var
  5.   MyArrayOfNumber: array of TNumber;
  6.   i: Integer;
  7. begin
  8.   SetLength(MyArrayOfNumber, ItemCount);
  9.   for i := 0 to ItemCount - 1 do
  10.     MyArrayOfNumber[i] := TNumber.Create;
  11. end;

If the array is a dynamic array, you first need to use SetLength to request space from the unused memory, see line #8. Read more: https://www.freepascal.org/docs-html/rtl/system/setlength.html

Because by default, Pascal array starts from 0, so 10 items of the array are actually started from 0 to 9, see line #9.

Before you can use the instance of the TNumber you have to call its constructor, in the example it is TNumber.Create, see line #10.

Seenkao

  • Hero Member
  • *****
  • Posts: 545
    • New ZenGL.
Re: External: SIGSEGV
« Reply #7 on: December 23, 2021, 05:51:13 am »
Товарищи англичане, не хотите воспользоваться переводчиком и предоставить перевод на не английском форуме?

Очень интересно получается, что все должны переводить на английский, на англоязычном форуме, а вы не можете перевести когда находитесь на не англоязычном форуме!!! >:D

Извиняюсь за эмоции! Просто напрягает, когда свои же правила не соблюдаем.  :-[

Google translate:
Comrades, Englishmen, do you want to use a translator and provide a translation on a non-English forum?

It turns out very interesting that everyone should translate into English, on an English-speaking forum, and you cannot translate when you are on a non-English-speaking forum !!! >:D

Sorry for the emotions! It's just annoying when we don't follow our own rules. :-[
Rus: Стремлюсь к созданию минимальных и достаточно быстрых приложений.

Eng: I strive to create applications that are minimal and reasonably fast.
Working on ZenGL

Zeno

  • Newbie
  • Posts: 6
Re: External: SIGSEGV
« Reply #8 on: December 23, 2021, 08:29:12 pm »
Handoko, спасибо за ответы на мои вопросы!

 

TinyPortal © 2005-2018