Alphabet, basic types and description of data. Object-oriented approach to programming


Size: px

Start showing from the page:

Transcript

1 Federal Agency for Railway Transport Ural State Transport University Department of Information Technologies and Information Security A. V. Kibardin PROGRAMMING IN C++ LANGUAGE Part 3 Basics of visual programming in the Borland C++ Builder environment Yekaterinburg Publishing house UrGUPS 2012

2 UDC (075.8) K38 K38 Kibardin, A. V. Programming in C++. In 3 hours. Part 3. Basics of visual programming in the Borland C++ Builder environment: educational method. allowance / A. V. Kibardin. Ekaterinburg: UrGUPS Publishing House, p. The manual is intended for learning the basics of visual design and event-oriented programming in algorithmic language C++ in the Borland C++ Bulder package environment. Aimed at students in the field of “Mechatronics and Robotics”, as well as undergraduates, graduate students, students of the Faculty of Education and the Preparatory Department, studying the basics of modern information technologies. UDC (075.8) Published by decision of the editorial and publishing council of the university Author: A. V. Kibardin, Associate Professor of the Department of Information Technologies and Information Security, Ph.D. physics and mathematics Sciences, USGUPS Reviewers: G. B. Smirnov, Professor of the Department of Computer Science, Doctor of Engineering. Sciences, UrFU named after. First President of Russia B.N. Yeltsin V.I. Radchenko, Professor of the Department of Information Technologies and Information Security, Doctor of Physics and Mathematics. Sciences, UrGUPS Ural State University of Transport and Communications (URGUPS), 2012

3 CONTENTS INTRODUCTION... 4 BASICS OF PROGRAMMING IN THE C++ BUILDER ENVIRONMENT... 5 WORKING WITH AN INTEGRATED APPLICATION DEVELOPMENT ENVIRONMENT..9 DEVELOPMENT OF THE PROGRAM INTERFACE. C++ BUILDER COMPONENTS DEVELOPMENT OF APPLICATION CODE. EVENTS AND EVENT HANDLERS.17 HANDLING EXCEPTIONAL SITUATIONS IN THE PROGRAM 20 DEVELOPING THE APPLICATION INTERFACE PREPARING THE APPLICATION FOR DISTRIBUTION WORKING WITH GRAPHICS WORKING WITH FILES WORKING WITH DATABASES SOME COMPONENTS FOR DISPLAY DATA LOSSES FROM DB QUESTIONS TO THE DATABASE PROGRAMMER COMPONENTS BIBLIOGRAPHICAL LIST

4 INTRODUCTION The rapid development of computer technology and the need for effective software development tools have led to the appearance on the software market of a number of programming systems focused on rapid application development, among which Microsoft Visual Basic and Borland Delphi should be noted. Rapid development systems are based on the technology of visual design and event-driven programming, the essence of which is that the development environment takes on most of the work of generating program code, leaving the programmer to design dialog boxes and write functions for processing events that occur in program. It is clear that such systems dramatically increase programmer productivity. The success and popularity of Delphi made Borland want to extend the rapid development method to the field of professional programming, which led to the emergence of Borland C++ Builder. C++ Builder is a rapid development environment that uses the extended C++ language (C++ Builder language) as the programming language. This tutorial describes event-driven and visual programming technologies in C++ in the C++ Builder environment. To work with methodological instructions, you must master the basics of programming in C++ and know the following technologies: structured programming; modular programming; object-oriented programming (OOP). C++ Builder is a rapid development environment in which, as a language, a large number of topics are devoted to these technologies. educational literature, including . 4

5 BASICS OF PROGRAMMING IN THE C++ Builder ENVIRONMENT Features of programming in the Windows environment The C++ Builder system is designed for developing programs that run in the Windows environment. Programming in Windows has the following features: 1) program code consists of procedures for processing messages that Windows sends to an application (program); 2) Windows records events occurring in programs and hardware and sends corresponding messages to the program; 3) several programs can be executed simultaneously. These programs share computer resources among themselves; 4) the running program is in the working memory area and waits for messages from Windows to which it must respond; 5) interaction with hardware occurs through GUI devices. Windows offers the program developer what is called an event-driven environment, where program code is executed in response to a specific event. Windows generates an input message for each input event generated by the user using the mouse or keyboard. Windows stores input messages in a queue system messages. These messages are then sent to the application's message queue. A message to a Windows application is generated by creating a message entry in the message queue. Some messages from Windows are sent directly to the application window; these are so-called out-of-order messages. An application can also create its own messages, place them in a message queue, and send them to other applications. Each application runs in its own window, which has a unique handle description. Since the message record indicates who it is intended for this message, then Windows forwards it to the specified address. The application must be able to process any message. For almost every event, Windows has a standard handling procedure. The application should specify that when an NM event occurs for which there is no specific code in the program, the standard Windows procedure should be executed. Most standard program messages are processed automatically because all C++ Builder objects have a built-in message handling procedure. 5

6 Basic concepts of OOP in C++ Builder Programming in C++ Builder is based on the extended C++ language (C++ Builder language). C++ introduces a special data type, class. A class is a data structure consisting of the following elements: fields; methods; properties. Fields contain data of a specific type. Methods are functions that perform specific actions. Properties are data fields that affect the behavior of an object. They differ from ordinary fields in that assigning values ​​to them involves calling the corresponding methods. The language uses the reserved word class to describe a class. The class is declared in the application module (see below). In C++, the base class for all classes is the abstract class TObject: therefore, if you need to create a new data class, you must use the following description: class TNewObject: TObject class body; We remind you that when describing a class, its header lists all the classes that are base for it. The ability to access elements of these classes is regulated using the private, protected and public access keys (see). An object is an instance of a class. An instance of a class is implemented by a variable of this type class, for example: TNewObject *NewObject; File management in C++ Builder At the beginning of work on a project, C++ Builder provides the developer with a virtually ready-made program. The program consists of one window with the title Form1 and has the functionality of a standard Windows window. This creates the following application files. The main project module Project1.cpp contains the code of the main program written in C++. The file contains links to all project forms and related modules. It also contains the application initialization code: 6

7 // #include #pragma hdrstop // USEFORM("Unit1.cpp", Form1); // WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int) try Application->Initialize(); Application->CreateForm(classid(tform1), &Form1); Application->Run(); catch (Exception &exception) Application->ShowException(&exception); catch (...) try throw Exception(""); catch (Exception &exception) Application->ShowException(&exception); return 0; // Form modules For each form, C++ Builder creates a separate module, which consists of two files: a header file and a code file (the contents of these files are shown in the code editor window). The header file Unit1.h contains a description of the form and looks like this: // #ifndef Unit1H #define Unit1H //

8 #include #include #include #include // class TForm1: public TForm published: // IDE-managed Components private: // User declarations public: // User declarations fastcall TForm1(TComponent* Owner); ; // extern PACKAGE TForm1 *Form1; // #endif The code file (form module) Unit1.cpp contains a description of functions, including event processing: // #include #pragma hdrstop #include "Unit1.h" // #pragma package(smart_init) #pragma resource "*.dfm" TForm1 *Form1; // fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner) // In addition, C++ Builder, analyzing the actions of the programmer, generates a file describing the properties of the form (forms, if there are more than one of them in the project) as a component of the standard library visual components Unit1.dfm, project file Project1.bpr and project resource file. The result of compiling the project ( executable application) is saved in the file Project1.exe. Files with the extension .tds and .obj are created by the compiler during the generation of the executable file. Backups project files have “~” (*.~*) as the first extension character. 8

9 WORKING WITH AN INTEGRATED APPLICATION DEVELOPMENT ENVIRONMENT The core of C++ Builder is the integrated application development environment (IDE). After launching C++ Builder, several windows will appear on the screen, shown in Fig. 1. The IDE consists of a main window, an object inspector, a visual form designer, a program editor window that includes a class viewer and a program source editor. The main window includes a main menu and several toolbars: standard, form and source text viewing panel, debugging panel, environment settings selection panel, custom panel, and component palette. The component palette includes 19 panels. Components focused on a specific application area are combined within one panel. Each component is represented in the palette by its own icon. Visual form designer A form is a future Windows window that houses various controls (buttons, menus, text boxes, switches, etc.). When the created program is compiled and launched, the form turns into a regular Windows window and performs the actions that are defined for it by the developer. There may be several such windows in a program, but only one of them is considered the main window, the rest are auxiliary. Form components Palette components contain generalized images of control elements and have appropriate names (“button”, “scroll bar”, etc.). Once a component is placed on a form, it actually contains an instance of the corresponding component, that is, an object. Object Inspector The Object Inspector is designed to set the properties of objects and determine their reactions to various events. The current object is shown at the top of the inspector in a drop-down list. The Object Inspector contains two pages: “Properties” and “Events”. To change a specific property, you need to select an object on the form, click on the “Properties” page, then click in the line of the corresponding property and set its new value in the window that opens. The "Events" page of the inspector allows you to define the program's response to various events in the form of corresponding functions. 9

10 Main window Toolbars Inspector Viewer Visual Editor class objects designer of source code forms Fig. 1. Main window of the application development environment Program editor Next to the main form window is the program editor window. Switching between the form and the code editor can be done either with the mouse or with the “F12” function key. The editor window consists of two panels: the class viewer and the program source text editor. The class viewer visually displays the structure of connections between various program objects and allows you to quickly navigate through its text. The program code is displayed in the program source editor window. Intuitive coding assistant The code editor has a set of tools that provide a range of support functions. These tools are collectively called an intuitive coding assistant. It performs the following functions: code completion; 10

11 contextual list of parameters; quick estimation of values; tooltips about identifier declarations; code templates. Project Manager In addition to the main form and the module with the source code of this form, the program contains a project file with which you can manage files (modules) that are components of the project. The manager window is called by the View / Project Manager command. The Project Manager allows you to perform operations on files. Actions with files are performed using the project manager toolbar. eleven

12 DEVELOPMENT OF THE PROGRAM INTERFACE. C++ BUILDER COMPONENTS Developing Windows applications with C++ Builder is very easy because the developer has an extensive object library (VCL) at his disposal. This library is built on a hierarchical principle and is based on the TObject class. This is an abstract type defined in the Classes module. It is the ancestor of all objects: all objects are derived from it and have properties inherited from TObject. The C++ Builder object hierarchy is shown in the following diagram. Object Non-Visual Visual Non-control Control Windowed Non-Windowed C++ Builder Components are a special kind of object. Components, along with methods and event handlers, have properties. Properties have preset values ​​that can be changed both during program execution and during program development. The difference between components and objects is that components are visual objects; they can be edited during program development, but non-visual objects cannot. For example, a RadioButton is a visual object that is graphically represented in the Components palette. Controls are a special type of component. Components that do not act as controls are invisible to the user; he can't do anything with them. For example, the menu component is visible and accessible only to the application developer. When working with the application, the user cannot do anything with the menu component. He sees only the result of the programmer’s work with this component, namely a menu in which you can select something. On the contrary, a button is a graphic element, visible user. The user can perform some action, such as clicking on a given button. Within the control category, there is a distinction between windowed and non-windowed controls. Window controls are those that: can become active; may contain other controls; 12

13 have a window handle. Non-windowed controls are those that: cannot become active; cannot contain other controls; do not have a window handle. Let's create an application that can calculate the roots of a quadratic equation. Let's start with developing the user interface of the program. Launch the C++ Builder programming system and immediately save the project file and module file using the File menu command. Since the system creates many working files for your project, you should save them in a separate folder. Let's note the fact that you already have a working application that displays a blank window. With this window you can do the usual for windows Windows actions. Verify this by launching the application using the Run / Run menu command. In the program, the user will need to enter the equation coefficients a, b and c. To enter this data, we will use the Edit component (input field). The component is placed on the Standard tab of the component palette. Click the Edit component button, then move the mouse cursor over the form and click in the desired location. As a result of these actions, an input field will appear on the form with the inscription Edit1 inside. In this case, the input field itself will receive the name Edit1, under which it will be available to the program. Object names are created automatically in C++Builder according to the following principle: the name of the component plus the serial number of the control placed on the form. The form with all controls is shown in Fig. 2.!!! The program developer can assign his own names to the controls, but this should only be done through the Object Inspector, and not in the code editor. To do this, you need to select the Name property of the desired element in the Object Inspector and set a new name. Let's clear the contents of the input field from the label. To do this, select the input field on the form by clicking on it with the mouse cursor, and on the “Properties” page of the object inspector select Text property input fields and in the adjacent cell, delete the text Edit1. Let's place an inscription above the input field, explaining that this input field is intended for entering the coefficient a. Let's use the Label component. This component is located on the “Standard” tab. To set the caption, use the Caption property of this control. Similarly, place the input fields for coefficients b and c on the form and make appropriate inscriptions above them. The results of the calculations, i.e. the values ​​of the calculated roots x1 and x2, can be displayed on the form using the Edit and 13 components already known to you

14 Label. Place two more Edit elements and corresponding labels above them on the form. Rice. 2. View of the project window Let's place two buttons on the form: one to start the calculation process, the second to end the program. Let's use the Button component. The Button component is also located on the Standard tab. Let's set the labels on the buttons: “Calculate” and “Close”. To do this, use the Caption properties of the corresponding buttons. Let's place on the form such important interface elements as the menu bar, toolbar and status bar. Go to the "Win32" tab of the component panel and click on the ToolBar icon, then click on the form with the mouse cursor. A toolbar will appear at the top of the form, without any buttons yet. To create toolbar buttons, we will use the SpeedButton component located on the “Additional” tab. Place three buttons on the toolbar that correspond to the Calculate, Help, and Exit commands. Highlight the desired button and use the Glyph property. Then click on the three-dot rectangle in the property bar. As a result, the editor dialog box 14 will appear

15 pictures. In this window, click the “Load” button; find the Program Files\Common Files\Borland Shared\Images\Buttons subdirectory and select from the list of suggested files suitable drawing. In the editor window, click OK. Return to the "Win32" tab and highlight the StatusBar icon. Click the mouse cursor on the form. A status bar will appear at the bottom of the form. Go to the Standard tab of the Components palette and highlight the MainMenu icon. Click the mouse cursor anywhere on the form. The MainMenu component is non-visual, so it can be located anywhere on the form. Double click on the menu object and the menu editor will appear on the screen. In order to use it to add new menu items, you must perform the following steps: 1) press the “Enter” key, the object inspector will be activated, which will prompt you to enter a name for the current menu item in the Caption line; 2) enter the word “Equation” and press “Enter”. The system will switch back to the menu editor. Press Enter and in the Object Inspector, type the word “Calculate.” Repeat these steps twice more to add Help and Exit sub-items to the menu. To complete the development of the program interface, it remains to add one more form with the necessary controls. The second form will be the program's help window. Use the menu command File/New/Form to add a second form to the project. Change the title of the form to "Help". Place a Memo1 object on the form using the Memo component (multi-line input field) on the “Standard” tab. This component allows you to display text consisting of many lines. Set the form and Memo1 field to appropriate sizes. To do this, select the desired object; black squares will appear at the edges of the object. By grabbing one of the squares with your mouse cursor, you can change the size of the object. Directly below the input field, place a button that closes the help window. To do this, use the BitBtn component on the “Additiona” tab. In its Kind property, select bkclose. This predefined value will close this window. All that remains is to place the help text in the input field. Select the Lines property of the input field, and then double-click the button with three dots in the line of this property. This will open a text editor window in which you should delete the field name and enter help text, such as the following: 15

16 This program calculates the roots of a quadratic equation. Enter the values ​​of the equation coefficients in the appropriate windows and click the “Calculate” button. To exit, click the “Exit” button. After entering the help text, click OK. Save the second form module. This completes the development of the interface. 16

17 DEVELOPMENT OF APPLICATION PROGRAM CODE. EVENTS AND EVENT HANDLERS Applications built with C++ Builder are Windows applications. One of the main properties of such applications is event management. This means that the program runs based on generated event messages that are processed by the application code. Such code must be written for each event to which the program must respond. A procedure designed to respond to an event is called an event handler function in C++Builder. There are two categories of events: events caused by user actions, user events, and regular events, software-controlled events. Functions for processing user events form the main part of the application code. They provide interactive interaction between the application and the user. C++Builder does this by using predefined event handlers that can be used by almost all components. This includes mouse and keyboard event handlers. Regular (software-controlled) events include activation events, termination events, events that change the state of individual components, and other events that are an indirect result of user action. C++ Builder generates functions to handle each event and names them according to the names of the components for which these procedures are intended. For example, if you double-click Button1, an empty event handling function will be generated in the form module, which looks like this: void fastcall TForm1::Button1Click(TObject *Sender) Next, you need to enter the required program code into the compound block. Select the Calculate button, go to the Events page in the Object Inspector, and double-click the name of the OnClick event handler. The system will add an empty button click processing function to the module text. What is this function supposed to do? Firstly, it must read the contents of the input fields for coefficients a, b and c; then the read values ​​must be converted into numbers, since the Text property of the Edit component has a string type; then the necessary calculations must be performed and the result placed in the Edit4 and Edit5 fields. 17

18 Add the code below to the function. void fastcall TForm1::Button1Click(TObject *Sender) float a,b,c,d,x1,x2; a=strtofloat(edit1->text); b=strtofloat(edit2->text); c=strtofloat(edit3->text); d=b*b-4*a*c; if (d>=0) else x1=(-b-sqrt(d))/(2*a); x2=(-b+sqrt(d))/(2*a); Edit4->Text=FloatToStr(x1); Edit5->Text=FloatToStr(x2); ShowMessage("No valid roots"); In the preprocessor directives section of the form module, add the line #include This header file will allow you to use a library of mathematical functions (in our case, the function of calculating the square root). Let us note the following points in the text. For calculations, we used only local variables, since they do not need to be used in other procedures. To convert a string of characters into a number and the reverse conversion, the StrToFloat() and FloatToStr() functions are used, respectively. To display the message “No valid roots”, use the Windows function of calling the dialog ShowMessage windows(). Let's define a function for processing a click on the "Exit" button. Double-click on this button and in the code editor window that appears, add line 18 to the Button2Click function

19 Form1->Close(); (Close() method closes our application window.) Save the project and run it. Check its operation under various initial data. If the system detects errors, correct them and run the project again. Let's now define menu events and button clicks on the toolbar. We don't need to write any code for this. We will connect the necessary events with already defined events by clicking on the “Calculate” and “Exit” buttons. Click on the menu bar and then select the first menu item, “Calculate.” In the Object Inspector, on the Events page, in the On-Click handler row, select the Button1Click function from the list of available functions. Click on the form and do the same with the “Exit” menu item, only now associate it with the Button2Click function. Select the “Help” menu item, double-click in the OnClick handler line in the object inspector, and add the Form2->ShowModal() command to the N3Click function in the code editor; In the module directives section of the main form, do not forget to add the directive to include the help module header file #include "help_module_name.h". Here help_module_name is the name with which you saved the module on disk. The ShowModal() method calls the help window, and until it is closed, you will not be able to go to the main application window (the modal state of the window). Select the “Calculate” button on the toolbar and in the object inspector for the OnClick handler, select the Button1Click function; for the Exit button the Button2Click function. For the Help button, create a procedure that handles the click in the same way you did for the Help menu item. It remains to determine the operation of the StatusBar1 status bar. Select it on the form, go to the Properties page of the Object Inspector, find the SimplePanel property and set it to true. Double-click on the form and place the following code in the body of the FormCreate function: void fastcall TForm1::FormCreate(TObject *Sender) StatusBar1->SimpleText="Enter the equation coefficients"; Save the project and check the application. 19

20 PROCESSING OF EXCEPTIONAL SITUATIONS IN THE PROGRAM In the developed program, we did not take into account possible data entry errors. First, the user can enter a sequence of characters that is not a number. Second, the user can enter a coefficient value of a = 0, which will result in an attempt to divide by zero in operators that calculate the roots of the equation. Both situations are called exceptional. Examples of other exception situations are overflow, an attempt to open a non-existent file, etc. To control such situations, the C++ Builder system has a so-called exception handling mechanism. When an exceptional situation occurs, the program generates a so-called exception and further calculations in this block are stopped. An exception is a special type of object that characterizes an exceptional situation that has arisen in a program. The peculiarity of exceptions is that they are purely temporary objects. As soon as they are processed by any handler, they are destroyed. If the exception is not caught anywhere in the program, then it is handled by the standard Tapplication.HandleException method. This method provides the user with brief information in a message window and destroys the exception instance. The most radical way to deal with exceptions is to handle them using logical try and catch blocks: try //statements that can cause an exception to occur catch (Type &e) //commands that handle this exception Here Type is the type (class) of the exception . C++Builder defines a number of exception classes. Let's consider two of them needed in our program: the EConvertError class, associated with an error in converting strings or objects (in particular, in the StrToFloat function), the EZeroDivdide class, associated with an attempt to divide a floating point number by zero. 20

21 Change the text of the Button1Click function to match the text below. void fastcall TForm1::Button1Click(TObject *Sender) float a,b,c,d,x1,x2; try a=strtofloat(edit1->text); b=strtofloat(edit2->text); c=strtofloat(edit3->text); catch(econverterror &e) ShowMessage("Error data!"); return; d=b*b-4*a*c; if (d>=0) try x1=(-b-sqrt(d))/(2*a); x2=(-b+sqrt(d))/(2*a); catch(ezerodivide &e) ShowMessage("Coefficient a cannot be equal to zero!"); return; Edit4->Text=FloatToStr(x1); 21

22 Edit5->Text=FloatToStr(x2); else ShowMessage("No valid roots"); Save changes to the module text and check for errors.!!! If you run a project and specify erroneous data, the debugger will catch the exception and program execution will be interrupted. Click the Run button again and you will see the exception handler you defined running. However, after you make a completed project, exceptions will be handled according to your program code. 22

23 DEVELOPING THE APPLICATION INTERFACE Let's finalize the interface of our program. First, we'll make tooltips appear for the toolbar buttons. Select the Calculate button on the toolbar and in the Object Inspector, set its Hint property to Calculate and its ShowHint property to true. Do the same for the remaining buttons. Save changes to the project. Now let's do it possible use"hot" keys when working with the menu. You can set “hot” keys in two ways: 1) specify a “hot” letter in the title of the menu item. To do this, click on the menu component and in the object inspector, in each menu item heading, place the & icon in front of the desired letter, for example: &Calculate “Hot” letters will be underlined; 2) select the ShortCut property for this menu item and select the desired Ctrl+letter combination from the drop-down list. Set hotkey combinations for menu items and save changes to the project. The last thing we need to do is set the transition sequence between controls when the TAB key is pressed. This is standard practice on Windows. Select all controls on the form and select “Tab Order” from the context menu. Use the arrow buttons to rearrange the list of items in the following order: Edit1, Edit2, Edit3, Button1 and click OK. Save changes to the project. After starting the program, the Edit1 input field will become active. By pressing the "TAB" key, you can move through the remaining input fields one by one.!!! Navigate through controls in reverse side can be done by simultaneously pressing the SHIFT and TAB keys. 23

24 PREPARING THE APPLICATION FOR DISTRIBUTION We have completed the development of the project and all that remains is to prepare it for distribution. Let's make the program window always appear in the center of the screen. Set the main form's Position property to poscreencenter. Let's select an icon for the program (until now we have used standard icon C++ Builder). The icon changes as follows: enter the command Project / Options; select the Application tab; click on the Load Icon button; Using the open file dialog, select the pre-prepared icon file (it must have a .ico extension). A large set of ready-made icons is available in the C++ Builder standard library in the \Images\Icons subdirectory. Select the desired picture and click on the “Open” button; in the Title line, enter the caption “Quadratic Equation”; Click on the "OK" button. A program created in C++ Builder uses a DLL version of the runtime library (RTL) and special dynamic library packages. In order for the program to work on another computer, you must transfer the library to this computer along with the exe file of this program or include the library and packages in the exe file. To do the latter, you need to do the following: 1) enter the Project / Options command and select the “Packages” tab, uncheck the “Build with runtime packages” checkbox; 2) select the “Linker” tab and uncheck the “Use dynamic RTL” checkbox. Now you need to recompile the project. Run the command Project Your_Project_Name / Build. Now in the project directory there is executable file your project (file with .exe extension) with connected libraries. 24

25 WORKING WITH GRAPHICS You can draw in the program directly on the surface of the form, or by selecting special areas on the form for drawing; this is done using the Image and PaintBox components. The form and the specified components have the Canvas property, which allows you to display graphics. For example, the operator Form1->Canvas->Rectangle(20, 20, 60, 60); draws a rectangle on the surface of the form. The following table lists the methods of the Canvas property that allow you to draw basic graphics primitives. Table 1 Methods for drawing graphic primitives Method MoveTo(x, y) LineTo(x1, y1) Polyline(points, n) Rectangle(x1, y1, x2, y2) y2) y2) FillRect(x1, y1, x2, Ellipse(x1 , y1, x2, Arc(x1, y1, x2, y2, x3, y3, x4, y4) Pie(x1, y1, x2, y2, x3, y3, x4, y4) TextOutA(x, y, text) Action Moves the cursor to position with given coordinates(coordinates are counted from the upper left corner of the form or drawing area) Draws a straight line from the current position to a point with coordinates (x1, y1) Draws a broken line; points array of line inflection points (see example below), n number of line nodes Draws a rectangle, x1, y1, x2, y2 coordinates of the upper left and lower right corners of the rectangle, respectively. Draws a filled rectangle Draws an ellipse. X1, y1, x2, y2 specify the coordinates of the rectangle into which the ellipse fits 1 2 Draws an arc. Parameters x1, y1, x2, y2 define the ellipse of which the arc is a part, x3, y3, x4, y4 define the starting and ending points of the arc. Draws a sector of an ellipse or circle. The sector is cut counterclockwise from the point with coordinates (x3, y3) to the point (x4, y4) Displays the text specified by the third parameter. Parameters x, y define the starting point from which the output begins 25

26 To display individual points, use the Pixels[x][y] property of the Canvas property. For example, the following statement displays a red point with coordinates (50, 50) on the form: Form1->Canvas->Pilxels=clRed; Here clred is a named constant corresponding to the color red. To color a point in an arbitrary color, use the RGB(red, green, blue) function, where the red, green, blue parameters specify the proportions of red, green and blue in the composition of a given color and can take values ​​in the interval (0, 255), for example: Form1->Canvas->Pilxels=RGB(0, 163, 78); The methods described above only provide drawing of graphic primitives. The type of graphic element is determined by the Pen and Brush properties of the surface (Canvas) on which it is drawn. this element. "Pencil" and "brush", being properties of the Canvas object, are themselves objects. The properties of Pen and Brush objects are described in the following tables. Table 2 Color Width Style Property Pen Object Properties Defines the Line Color Line Width (in pixels) Line Type. pssolid solid; psclear line is not displayed; psdash dotted with long strokes; psdot dotted with short strokes; psdashdot alternating long and short strokes Table 3 Properties of the Brush object Property Defines Color Color filling a closed area Style Style of filling the area. bssolid solid fill; bshorizontal horizontal hatching; bsvertical vertical hatch; bsfdiagonal diagonal shading with a forward slant; bsbdiagonal diagonal hatching with a backward slant; bscross into a cage; bsdiag- Cross diagonal cell The Font property of the “canvas” allows you to change the font parameters. The following table describes the properties of the Font object. 26

27 Property Name Size Style Color Table 4 Properties of the Font object Defines the font used. The value of the property is the name of the font, for example Arial Size in points Font style. Defined by the following constants: fsbold bold; fsitalic italics; fsunderline underlined; fsstrikeout crossed out Color of symbols. Set using named constants, such as clred, or using the RGB() function Example 1. Displays a red dot and a black straight line in the PaintBox drawing area when a button is pressed. Start a new project. Place a PaintBox component (Win32 tab) and a Button on the project form. For the button click processing function, write the following code: void fastcall TForm1::Button1Click(TObject *Sender) PaintBox1->Canvas->Pixels=clRed; PaintBox1->Canvas->MoveTo(50,50); PaintBox1->Canvas->LineTo(100,100); Example 2. Drawing a shaded circle directly onto the surface of the form. We use the OnPaint event handler (redrawing) of the form. For the OnPaint event handler function, write the following code: void fastcall TForm1::FormPaint(TObject *Sender) Form1->Canvas->Ellipse(40,40,140,140); Example 3: Using Pen and Brush Objects. Place another Button on the form. For the button click function, write the following code: 27

28 void fastcall TForm1::Button2Click(TObject *Sender) Form1->Canvas->Brush->Color=clRed; Form1->Canvas->Brush->Style=bsCross; Form1->Canvas->Pen->Width=3; Form1->Canvas->Ellipse(40,40,140,140); Example 4. Working with a font Use the OnPaint form creation event handler. Add text output code to the form redraw event processing function: void fastcall TForm1::FormPaint(TObject *Sender) Builder"); Form1->Canvas->Ellipse(40,40,140,140); Form1->Canvas->Font->Name= "Times New Roman"; Form1->Canvas->Font->Size=20; Form1->Canvas->Font->Color=clBlue; Form1->Canvas->TextOutA(100, 5, "Examples of working with graphics in C++ Save the project and check its operation.Task Write a program that displays a graph of the function y(x)=sin(x)e x/5 in a user-specified interval and with a given step in x. Component TStringGrid (table) This component allows you to display data on the form in the form of a table. Located on the “Additional” page. Cells Properties This property is an array of strings containing rows of table text. The parameters Acol, Arow indicate the column number and row number of the table, respectively. The first row and the first column are numbered zero. If A numeric value must be written to a table cell; it must be converted using the IntToStr() or FloatToStr() functions. 28

29 Example float x=2.4; StringGrid1->Cells="Argument value"; StringGrid1->Cells="Function value"; StringGrid1->Cells=FloatToStr(x); StringGrid1->Cells=FloatToStr(x*x); Cols This is an array containing rows for each column of the table. The number of rows is equal to the value of the RowCount property. ColCount Determines the number of table columns. The default is five. RowCount Determines the number of rows in the table. The default is five. Col Points to the column of the currently active cell. Row Points to the row of the currently active cell. DefaultColWidth DefaultRowHeight Determine the width of all columns and the height of all rows of the table, respectively. To change the height of individual rows and the width of individual columns, use the RowHeights and ColWidths properties. ColWidths RowHeights Allows you to change the width of the column and the height of the row with the Index number, respectively. DefaultDrawing Specifies whether table cells will be automatically drawn (true). EditorMode Determines whether the current table cell can be drawn. If the Options property set (see table below) contains the value goediting, then the table automatically switches to editing mode. The same thing happens when you set the EditorMode property to true. While Options values ​​are typically set during application development, the EditorMode property can be changed while the program is running. When the EditorMode property=true, the table is in editing mode if the Options set contains an element. Otherwise, cells cannot be edited. 29

30 If the EditorMode=false property and the Options set contains the goediting element, but not goalwaysshoweditor, then the user can switch to editing mode using the "F2" key. Options This property determines the appearance and functional properties of the table. Table 5 Some values ​​of the Options property Value Setting Action govertline true Vertical lines are displayed between columns gohorzline true Horizontal lines are displayed between rows gorangeselect true The user can select a block of cells. However, if the goediting element is specified, this is not possible godrawfocus- Selected false The active cell has a different color than the rest. The color is set in the Color property. If the property is true, then the active cell has the same color gorowsizing true The sizes of individual rows can be changed at runtime gocolsizing true The sizes of individual columns can be changed at runtime goediting true The user can edit the contents of a cell. Cannot select block GoTabs true You can move through cells using the + keys. gothumbtracking goalwaysshoweditor true true The table automatically goes into editing mode (provided that the Options set contains a goediting element) The visible part of the table scrolls synchronously with the movement of the slider on the table scroll bar 30

31 FixedColor Defines the color of fixed table columns and rows. FixedCols Defines the number of fixed table columns (one by default). Fixed columns remain visible when the user scrolls through other columns. FixedRows Defines the number of fixed table rows (one by default). TChart component (diagram) The component is designed to work with complex types of charts. Component properties are configured in the “Editing Chart” editor window. The editor is called double click by the Chart component (Fig. 3). Rice. 3. Chart editor window Series Properties Represents an array of charts (data series) displayed in the area of ​​the Chart component, where Index specifies the number of the data series. The index is counted from zero. For each chart placed in the Chart area, you can set following parameters: type; Name; axles; 31

32 legend; data source. The chart type is set on the Series page of the chart properties editor. If the chart values ​​are generated while the application is running, then you must select the No Data option for the data source on the “Series-DataSource” page of the editor. To add a series (data series), click the Add button in the editor window and select the chart type in the window that appears (for example, Fast Line). To set series titles (they will be used in the legend to distinguish graphs) Click the “Title” button in the same window; it will become available after setting the required number of series (Fig. 4). Rice. 4. Dialog window of the diagram editor On the “Axis” tab, the names of the axes are set. The “Left” option corresponds to the Y axis, the “Bottom” option corresponds to the X axis. To label the axes, use the Title page on the “Axis” tab. To set the chart title, select the “Titles” tab. Methods The Add, Clear, and Delete methods are often used to control the values ​​used to construct the chart. Add(AValue, ALabel, AColor) Adds the value specified by the AValue parameter to the chart; the ALabel parameter specifies the name of the value (i.e., the X-axis label); the AColor parameter specifies the color. AddXY(XValue,YValue, XLabel, AColor) 32

33 Adds the value to the chart specified by the XValue, YValue parameters (i.e., the coordinates of the point); the remaining parameters have the same meaning as for the Add function. Example. A graph of the function y=x^2 is constructed in the interval for(int i=0; i<10; i++) Chart1->Series->AddXY(i, i*i); Delete(ValIndex) Deletes values ​​with the ValIndex number from the chart. Clear() Removes all values ​​from the chart. Example Chart1->Series->Clear(); Task Write a program that calculates a table of values ​​of the functions y1(x)= sin(x) and y2(x)= cos(x) in the interval of values ​​a x b, x changes with step dx, and plots graphs of the functions. The boundaries of the interval and the step of change dx are specified by the user. 33

34 WORKING WITH FILES The C++ Builder environment offers three ways to work with files: working with streams using the I/O functions of the C library, working with streams in the C++ style, and using the methods of dialog components of the development environment. Let's solve the following problem: create a Notepad program that allows you to type text, save it and read the prepared text text file. Launch the C++ Builder programming system. Place on the form a multi-line Memo input field (text will be typed in it) and four Buttons, to which give names: “Clear”, “Write”, “Read”, “Exit”. To save and search files, use the SaveDialog and OpenDialog components. Place these components anywhere on the form, as they are non-visual. A possible form is shown in Fig. 5. Fig. 5. Notepad window You have already worked with the Memo component, but let’s look at its properties and methods in more detail. The Clear() method clears the input window. The lines placed in the window are accessed through the Lines property, which represents an array of lines. The Count property stores the number of rows (the number of array elements). The counting of line numbers starts from zero. The Add(s) method adds string s to the list. The Delete(n) method deletes line number n. The Insert(n, s) method inserts a new string s between the elements of the list at position n. 34

35 The SaveToFile("path/file_name") method allows you to save the data stored in the Memo field to the specified file. The LoadFromFile("path/filename") method allows you to read data stored in the specified file into the Memo field. Let’s create a function for processing a click on the “Clear” button. The text of the function is presented below. void fastcall TForm1::Button1Click(TObject *Sender) Memo1->Clear(); // Let's also create a procedure for processing a click on the "Exit" button. We use the Close method to complete work with the application. void fastcall TForm1::Button4Click(TObject *Sender) Form1->Close(); // Before developing functions for processing the remaining events, we will describe working with the SaveDialog and OpenDialog dialog boxes. The Execute() method is used to call windows. The FileName property stores the name of the file. The Filter property allows you to configure filters for searching files. The DefaultExt property allows you to define an extension that will be automatically added to the file name. Let’s create a function for processing a click on the “Save” button. The text of the function is given below. void fastcall TForm1::Button3Click(TObject *Sender) SaveDialog1->DefaultExt="txt"; if (SaveDialog1->Execute()) Memo1->Lines->SaveToFile(SaveDialog1->FileName); 35

36 // Create a function for processing a click on the “Read” button. The text of the function is presented below. void fastcall TForm1::Button2Click(TObject *Sender) OpenDialog1->DefaultExt="txt"; if (OpenDialog1->Execute()) Memo1->Lines->LoadFromFile(OpenDialog1->FileName); // Save the project and check if it works. If there are no errors in the project, make an alienable application. 36

37 WORKING WITH DATABASES Configuring Borland DataBase Engine (BDE) BDE is a database processor (DB); it defines the data access technology. BDE administrator 5.0 BDE administrator is a program for setting up the BDE configuration. The program is launched using the main Windows menu command Start / Programs / Borland C++ Builder / BDE administrator. The main program window contains two panels. The left one includes a notepad with two pages that present the following settings options: DataBases; Configuration The right pane contains a notepad with a Definiton page that appears when you select an option in the left pane. The list of properties is divided into two parts: Type contains the name of the parameter; The left one contains the parameter value. Configuring global aliases The first page in the left pane of the BDE administrator window is intended for viewing, adding, deleting and modifying aliases and their parameters, providing access to the corresponding databases in an easier way. An alias in the database tree can be in the following states: closed, open, modified and created. To add an alias, use the Object / New menu command. In the window that appears, in the “DataBase Driver Name” line, select the STANDART value to create a database in the Paradox, Dbase or FoxPro format, or the MSACCESS value to create a database in the MS ACCESS format. Each alias has a set of properties. For aliases created based on the STANDART driver, they are as follows: TYPE driver name; DEFAULT DRIVER driver name; ENABLED BCD flag for converting decimal field values ​​to BCD; PATH is the path to the folder where the database tables are located. A private alias can be renamed or deleted using the menu command Object / Rename Object / Delete. 37


Lecture 24 Introduction to object-oriented programming Objects and classes The basic concepts of OOP in C++ are the object. An object is a certain program unit that combines properties (attributes)

MS Access. Forms Lectures on the discipline “Fundamentals of Programming and Information Technologies”, given at the Department of FMEG of the Faculty of Physical Education of NTU “KhPI” 1 Forms There are three ways to enter information into Access:

Practice 3 Creating a Form A form is a database object that can be used to enter, change, or display data from a table or query. Forms can be used to manage

Working with tables 1. Converting text into a table. a) Insert delimiters, such as commas or tabs, where text needs to be broken into columns. Use a paragraph mark to indicate

Working with standard document templates Cognitive Technologies User Guide Moscow, 2015 2 ABSTRACT This document provides information about the use of the E1 Euphrates software package

EDITOR OF VISUAL BASIC Gedranovich Valentina Vasilievna June 28, 2012 Abstract Chapter 18 from UMK: Gedranovich, V.V. Fundamentals of computer information technologies: educational method. complex / V.V. Gedranovich,

LECTURE-1. INTRODUCTION PURPOSE, COMPOSITION AND BASIC ELEMENTS OF THE INTERFACE OF APPLICATION SOFTWARE FOR PROCESSING BUSINESS INFORMATION Questions: 1. The concept of software and its classification

Topic 8 Styles A style is a set of formatting options that has a name. Styles are used: - for professional document design; - to quickly change text parameters; - to give uniformity

Laboratory work 12. Topic: Multi-window applications. Modal and modeless windows. Key issues: Application of several forms in projects. Consideration of different types of windows, modal and non-modal.

Laboratory work 7 Topic: Stylish formatting of documents. Creating a table of contents. Using Styles When creating a document, you often have to deal with headings. Typically the headings

Scroll bars 3 LAB 1 HELP SYSTEM AND RUNNING PROGRAMS IN WINDOWS. Tasks: Turn on your computer and boot into the Windows operating system. On the desktop surface, find the panel

6. PAINT PROGRAM 6.1. General information The Paint program is one of the most popular graphic editors among novice users. It is intended for viewing, creating and editing

State Budgetary Educational Institution of Higher Professional Education "Smolensk State Medical Academy" of the Ministry of Health of the Russian Federation Faculty of Dentistry Department of Physics, Mathematics and Medical Informatics Discussed

OpenOffice.org Impress Impress is a program included in OpenOffice.org for working with slide shows (presentations). You can create slides that contain many different elements, including text, bullets

INSTRUCTIONS FOR THE HTML EDITOR CKEDITOR Description of the CKeditor editor Text formatting 1. CKeditor editor services 2. Font styles 3. Text structuring 4. Text alignment 5. Inserting links,

Chapter 3 Microsoft Office 2013 Suite In this chapter, we will look at the work of some of the applications included in Microsoft Office 2013. The scope of this book does not allow for an in-depth study of working with these

Table of contents. 1 WORD TEXT EDITOR...2 TOOLBARS...2 HELP SYSTEM...2 BASICS OF WORKING WITH TEXT...2 INSERTING TEXT...2 DELETING TEXT...2 SELECTING TEXT...2 REPLACING SELECTED TEXT

WORKING WITH THE MICROSOFT ACCESS DATABASE MANAGEMENT SYSTEM 1 BASIC TERMS Query - Queries are a powerful tool for processing data stored in Access tables. Using queries, you can view

Ministry of Railways of the Russian Federation Moscow State Transport University (MIIT) Department of “Power supply of electric railways” Approved by the editorial and publishing

BASICS OF WORKING IN MICROSOFT ACCESS. DATABASE DESIGN. DATABASE CREATION. CREATION OF FORMS, REPORTS, QUERIES 1. Designing databases 2. Creating a database 3. Creating forms, reports, queries

Basics of working in MS Word 2007 Description of the program window After starting the MS Word program, its window opens on the screen. The window title says the name of the open file or Document1, Document2, if

How to open Microsoft Word 2010 3. Basics of working in Microsoft Word 2010 Microsoft Word is a multifunctional text processing program (editor) and desktop publishing system. In Word we

2 10 Creating graphical applications in the Scilab environment Scilab allows you to create not only conventional programs for automating calculations, but also visual applications that will run in the Scilab environment.

Tambov regional state budgetary educational institution average vocational education"Instrument Engineering College" Word processor interface Microsoft Word 2007 Concept

Practical work 4 “Reference book”, Page-1, Total - 6 Practical work 4, REFERENCE BOOK Statement of the problem Create a program that performs the following actions. After starting the program, the user selects

REGIONAL STATE BUDGET EDUCATIONAL INSTITUTION OF SECONDARY VOCATIONAL EDUCATION “SMOLENSK AUTO TRANSPORT COLLEGE named after E.G. Trubitsyn" METHODOLOGICAL INSTRUCTIONS for preparation for implementation

TEST: "DBMS ACCESS 2007 - CONTROL TEST". Task #1 How many fields are selected for inclusion in the generated REPORT Select one of 5 answer options: 1) 1 2) 2 3) 3 4) 4 5) 5 Task #2 Will the specified

Practical lesson 1 Creating custom VBA forms When working in Excel, as in most other applications, you have to deal with interface elements such as dialog boxes. Conversational

Introduction to Open Office OO is a complex office system designed for typing, editing and formatting text documents of any complexity. In addition to text documents, Open Office allows

Municipal educational institution secondary school 7, Kolomna, Moscow region Development of a lesson on studying the OOP Delphi environment on the topic: “General properties of some components”

Introduction to Micrsft Excel 1. Table structure 1. A spreadsheet consists of cells located at the intersection of rows and columns. Rows are numbered with numbers, columns - with Latin letters. Each cell

LECTURE 7. TOTAL COMMANDER PROGRAM Purpose of work: Studying the principles of the file manager Total Commander. Total Commander file manager provides another way to work with files and folders

Work 10 Tables and diagrams in Word. Calculations in tables Objective of the work: learn to insert tables and charts into a document, perform calculations in tables Contents of the work: 1 Entering and formatting tables

Laboratory work 2. Basics of working with MathCAD MathCAD, like most other programs, works with documents. From the user's point of view, a document is a blank sheet of paper on which you can place

Laboratory work 1. Topic. Fundamentals of object-oriented programming. Borland Delphi visual programming system. Creation of the program interface. Setting form (window) properties. Basic

Standard Components Library Manager CSoft Development, 2009. All rights reserved Contents Standard Components Library Manager...2 Security Note...4 Starting the Library Manager

Feature labels in ArcMap Labels are any text that helps you identify features on a map and better understand the contents of the map. ArcMap lets you label spatial

JSC "Baumann" APPROVED RU.74533456.00009-02 34 01-LU Integrated security complex "KODOS" Program "Mnemonic diagram" Operator's manual RU.74533456.00009-02 34 01 2015 CONTENTS 1 GENERAL PROVISIONS...

Purpose of the program Automation of all types of actions with texts. Functions: creation, editing, formatting, saving, processing and printing. Word 2007 professional text editor,

PRACTICAL LESSON 5 TOPIC: Integrated use of the capabilities of MS Word to create large documents OBJECTIVE: Learn to comprehensively use the capabilities of MS Word to create large documents

Laboratory work 8 “Technology of working in the Explorer program” Purpose of the work: to study techniques for working with the Explorer program 1. Brief theoretical information The Windows XP operating system includes

Chapter 8 Creating and Using Forms As noted in Chapters 1 and 2 of this book, database objects such as forms are designed primarily to work with only one record at a time.

LABORATORY WORK 1. 1. Entering the VB environment To enter the VB environment, use the Developer tab of the Excel window, which is located in the same row as the Home, Insert, etc. tabs. If it is missing, you should perform

VERTICAL-Reports System for generating technological documentation User's manual Information contained in this document, subject to change without prior notice. No part

Working with the ABBYY FineReader Bank program 7 ABBYY User Guide 2013 Processing documents in the ABBYY FineReader Bank program consists of four stages: Loading Recognition Verification Unloading

PROGRAM “MEMORY MODULES MANAGER” V 1.0.0 OPERATION MANUAL CONTENTS 1. Description of the program 3 1.1. Purpose of the program 3 1.2. System requirements 3 1.3. Installing the program 3 2. Custom

Deleted: 1C-Bitrix: Site Management 6.x Guide to creating and placing web forms on a site Contents Introduction...3 Creating a web form in a simplified mode...3 Adding a web form...4 Creating questions

164 1C:Enterprise 8.2. Developer's Guide Or you can select them from the drop-down list available when you are in the form module (Figure 5.19). Rice. 5.19. List of form events In this

Module 2. The computer as a set of hardware and software APPENDIX 2 Loading the operating system After turning on the computer, some time must pass before it is ready for use.

CONTENTS Chapter 13: PLACEMENT OF MULTIPLE CHARTS Contents OVERVIEW...2770 AUTOMATICALLY PLACEMENT OF MULTIPLE CHARTS WIZARD...2771 Using the Automatic Placement of Multiple CHARTS Wizard window

Practical lesson. “Working with styles and templates. Creating an automatic table of contents and a list of illustrations" Formatting styles and creating templates. 1) Launch MS Word. 2) Set the following

Practical work 6 Preparation of documents using word processors like Microsoft Word Objective: To become familiar with the features of electronic documents and the means for editing them in the environment

FAR MANAGER SOFTWARE SHELL Plan: Software shells. Far Manager Launching FM and interface elements FM Panels Function keys FM Menu Selecting panel presentation using the Sorting Objects menu

Stages of database development As a rule, non-professionals work with databases, so the following requirements for the database can be formulated. Developers, when creating a database, should focus on these

Brief instructions for working with Microsoft PowerPoint Action Algorithm Where to start? Starting a program 1. On the taskbar, click the Start button. 2. In the menu that opens, click the Programs command.

Laboratory work 8 “Configuring the parameters of computer peripheral devices” Purpose of work: obtaining information on setting up the user interface of peripheral devices using the operating system

The lecture texts discuss the basic principles and tools of object-oriented programming using the C++ language and the Borland C++ programming system. The appendix contains tasks for you to solve on your own. It is assumed that the reader is already familiar with the basics of general-purpose programming languages. The manual is intended for students of the specialty "Applied Mathematics" and can be used by students of other specialties for independent study of C++.

1. Object-oriented approach to programming

1.1 Programming technologies

Programming technology is a set of methods and tools for developing (writing) programs and the procedure for using these methods and tools.

In the early stages of programming, when programs were written as sequences of machine instructions, there was no programming technology. The first steps in developing the technology consisted of representing a program as a sequence of statements. Writing a sequence of machine instructions was preceded by drawing up an operator diagram reflecting the sequence of operators and the transitions between them. The operator approach made it possible to develop the first programs to automate the compilation of programs - the so-called program components.

With the increase in the size of programs, their separate parts began to be identified and designed as subroutines. Some of these subroutines were combined into libraries, from which subroutines could be included in working programs and then called from working programs. This marked the beginning of procedural programming - big program was represented by a set of procedures-subroutines. One of the subroutines was the main one, and program execution began with it.

In 1958, the first programming languages, Fortran and Algol-58, were developed. A Fortran program consisted of a main program and a number of procedures - subroutines and functions. The program in ALGOL-58 and its subsequent version ALGOL-60 was a single whole, but had a block structure, including a main block and nested blocks of subroutines and functions. Compilers for Fortran provided separate translation of procedures and their subsequent integration into a working program; the first compilers for Algol assumed that the entire program was translated at once; separate translation of procedures was not provided.

The procedural approach required structuring the future program, dividing it into separate procedures. When developing a separate procedure, you only needed to know about other procedures their purpose and how to call them. It became possible to rework individual procedures without affecting the rest of the program, while reducing the cost of labor and computer time for developing and modernizing programs.

The next step in deepening the structuring of programs was the so-called structured programming, in which the program as a whole and individual procedures were considered as sequences of canonical structures: linear sections, cycles and branches. It became possible to read and check a program as a sequential text, which increased the productivity of programmers when developing and debugging programs. In order to increase the structure of the program, requirements were put forward for greater independence of subroutines; subroutines should communicate with the programs that call them only by passing them arguments; the use of variables in subroutines that belong to other procedures or main program, began to be considered undesirable.

Procedural and structured programming affected, first of all, the process of describing an algorithm as a sequence of steps leading from varying input data to the desired result. To solve special problems, programming languages ​​began to be developed, focused on a specific class of problems: database management systems, simulation modeling, etc.

When developing translators, more and more attention has been paid to detecting errors in the source code of programs, thereby reducing the time spent on debugging programs.

The use of programs in various areas of human activity has led to the need to improve the reliability of all software. One of the directions for improving programming languages ​​has been to increase the level of data typing. Data type theory assumes that every data used in a program belongs to one and only one data type. The type of a datum defines the set of possible values ​​for the datum and the set of operations allowed on this datum. In some cases, data of a particular type can be converted into data of another type, but such a conversion must be explicitly represented in the program. Depending on the degree of fulfillment of the listed requirements, we can talk about the level of typing of a particular programming language. The desire to increase the level of typing of a programming language led to the emergence of the Pascal language, which is considered a strongly typed language, although it does allow some implicit type conversions, for example, integer to real. The use of a strictly typed language when writing a program makes it possible to identify many errors in data usage even when translating the source text and thereby increase the reliability of the program. At the same time, strict typing constrained the programmer's freedom and made it difficult to use some data conversion techniques often used in system programming. Almost simultaneously with Pascal, the C language was developed, more oriented towards system programming and related to weakly typed languages.

All universal programming languages, despite differences in syntax and keywords used, implement the same canonical structures: assignment operators, loops and branches. In all modern languages there are predefined (basic) data types (integer and real arithmetic types, character and, possibly, string type), it is possible to use data aggregates, including arrays and structures (records). For arithmetic data, ordinary arithmetic operations are allowed; for data aggregates, only the assignment operation and the ability to access the elements of the aggregate are usually provided. At the same time, when developing a program to solve a specific applied problem, it is desirable to have as close a conceptual proximity of the program text as possible to the description of the problem. For example, if solving a problem requires performing operations on complex numbers or square matrices, it is desirable that the program explicitly include operators for adding, subtracting, multiplying and dividing data of the complex number type, and adding, subtracting, multiplying and inverting data of the square matrix type. There are several ways to solve this problem:

By constructing a programming language containing as many data types as possible, and choosing a subset of this language for each class of problems. This type of language is sometimes called a shell language. The PL/1 language claimed the role of a shell language, but it turned out to be so complex that it was never possible to construct a formalized description of it. The lack of a formalized description, however, did not prevent the widespread use of PL/1 both in Western Europe, and in the USSR.

The construction of an extensible language that contains a small core and can be extended to complement the language with data types and operators that reflect the conceptual essence of a specific class of problems. Such a language is called a core language. The languages ​​Simula and Algol-68 were developed as core languages; they were not widely used, but had a great influence on the development of other programming languages.

A further development of the second path was the object-oriented approach to programming, discussed in the next paragraph.

1.2. The essence of the object-oriented approach to programming

The main ideas of the object-oriented approach are based on the following principles:

A program is a model of some real process, part of the real world.

A model of the real world or part of it can be described as a set of objects interacting with each other.

An object is described by a set of parameters, the values ​​of which determine the state of the object, and a set of operations (actions) that the object can perform.

Interaction between objects is carried out by sending special messages from one object to another. A message received by an object may require certain actions to be taken, such as changing the state of the object.

Objects described by the same set of parameters and capable of performing the same set of actions constitute a class of objects of the same type.

From a programming language perspective, a class of objects can be thought of as a type of a datum, and an individual object can be thought of as a datum of that type. The definition by the programmer of his own object classes for a specific set of tasks should allow him to describe individual tasks in terms of the task class itself (with an appropriate choice of type names and object names, their parameters and performed actions).

Thus, the object-oriented approach assumes that when developing a program, the classes of objects used in the program must be determined and their descriptions must be constructed, then instances of the necessary objects must be created and the interaction between them must be defined.

It is often convenient to structure object classes so that they form a hierarchical structure. For example, the class “Student”, which describes an abstract student, can serve as the basis for constructing the classes “1st year student”, “2nd year student”, etc., which have all the properties of a student in general and some additional properties that characterize a student of a specific course. When developing a user interface, programs can use objects of the general “Window” class and objects of classes of special windows, for example, information message windows, data entry windows, etc. In such hierarchical structures, one class can be considered as the base class for other classes derived from it. An object of a derived class has all the properties of the base class and some properties of its own, and it can respond to the same types of messages from other objects as an object of the base class and to messages that are meaningful only to the derived class. It is commonly said that an object of a derived class inherits all the properties of its base class.

Programming technologies. The essence of the object-oriented approach to programming. Purpose of Xi, historical information. Alphabet, basic types and description of data. Structures and associations. C++ operators. Functions. Runtime library.

Send your good work in the knowledge base is simple. Use the form below

Students, graduate students, young scientists who use the knowledge base in their studies and work will be very grateful to you.

Object-oriented programming in Borland C++

Texts of lectures given at the Moscow State University of Economics, Statistics and Informatics

The lecture texts discuss the basic principles and tools of object-oriented programming using the C++ language and the Borland C++ programming system. The appendix contains tasks for you to solve on your own. It is assumed that the reader is already familiar with the basics of general-purpose programming languages. The manual is intended for students of the specialty "Applied Mathematics" and can be used by students of other specialties for independent study of C++.

1. Object-oriented approach to programming

1.1 Programming technologies

Programming technology is a set of methods and tools for developing (writing) programs and the procedure for using these methods and tools.

In the early stages of programming, when programs were written as sequences of machine instructions, there was no programming technology. The first steps in developing the technology consisted of representing a program as a sequence of statements. Writing a sequence of machine instructions was preceded by drawing up an operator diagram reflecting the sequence of operators and the transitions between them. The operator approach made it possible to develop the first programs to automate the compilation of programs - the so-called program components.

With the increase in the size of programs, their separate parts began to be identified and designed as subroutines. Some of these subroutines were combined into libraries, from which subroutines could be included in working programs and then called from working programs. This marked the beginning of procedural programming - a large program was represented by a collection of subroutine procedures. One of the subroutines was the main one, and program execution began with it.

In 1958, the first programming languages, Fortran and Algol-58, were developed. A Fortran program consisted of a main program and a number of procedures - subroutines and functions. The program in ALGOL-58 and its subsequent version ALGOL-60 was a single whole, but had a block structure, including a main block and nested blocks of subroutines and functions. Compilers for Fortran provided separate translation of procedures and their subsequent integration into a working program; the first compilers for Algol assumed that the entire program was translated at once; separate translation of procedures was not provided.

The procedural approach required structuring the future program, dividing it into separate procedures. When developing a separate procedure, you only needed to know about other procedures their purpose and how to call them. It became possible to rework individual procedures without affecting the rest of the program, while reducing the cost of labor and computer time for developing and modernizing programs.

The next step in deepening the structuring of programs was the so-called structured programming, in which the program as a whole and individual procedures were considered as sequences of canonical structures: linear sections, cycles and branches. It became possible to read and check a program as a sequential text, which increased the productivity of programmers when developing and debugging programs. In order to increase the structure of the program, requirements were put forward for greater independence of subroutines; subroutines should communicate with the programs that call them only by passing them arguments; the use in subroutines of variables belonging to other procedures or the main program was considered undesirable.

Procedural and structured programming affected, first of all, the process of describing an algorithm as a sequence of steps leading from varying input data to the desired result. To solve special problems, programming languages ​​began to be developed, focused on a specific class of problems: database management systems, simulation modeling, etc.

When developing translators, more and more attention has been paid to detecting errors in the source code of programs, thereby reducing the time spent on debugging programs.

The use of programs in various areas of human activity has led to the need to improve the reliability of all software. One of the directions for improving programming languages ​​has been to increase the level of data typing. Data type theory assumes that every data used in a program belongs to one and only one data type. The type of a datum defines the set of possible values ​​for the datum and the set of operations allowed on this datum. In some cases, data of a particular type can be converted into data of another type, but such a conversion must be explicitly represented in the program. Depending on the degree of fulfillment of the listed requirements, we can talk about the level of typing of a particular programming language. The desire to increase the level of typing of a programming language led to the emergence of the Pascal language, which is considered a strongly typed language, although it does allow some implicit type conversions, for example, integer to real. The use of a strictly typed language when writing a program makes it possible to identify many errors in data usage even when translating the source text and thereby increase the reliability of the program. At the same time, strict typing constrained the programmer's freedom and made it difficult to use some data conversion techniques often used in system programming. Almost simultaneously with Pascal, the C language was developed, more oriented towards system programming and related to weakly typed languages.

All universal programming languages, despite differences in syntax and keywords used, implement the same canonical structures: assignment operators, loops and branches. All modern languages ​​have predefined (basic) data types (integer and real arithmetic types, character and, possibly, string types), and it is possible to use data aggregates, including arrays and structures (records). For arithmetic data, ordinary arithmetic operations are allowed; for data aggregates, only the assignment operation and the ability to access the elements of the aggregate are usually provided. At the same time, when developing a program to solve a specific applied problem, it is desirable to have as close a conceptual proximity of the program text as possible to the description of the problem. For example, if solving a problem requires performing operations on complex numbers or square matrices, it is desirable that the program explicitly include operators for adding, subtracting, multiplying and dividing data of the complex number type, and adding, subtracting, multiplying and inverting data of the square matrix type. There are several ways to solve this problem:

By constructing a programming language containing as many data types as possible, and choosing a subset of this language for each class of problems. This type of language is sometimes called a shell language. The PL/1 language claimed the role of a shell language, but it turned out to be so complex that it was never possible to construct a formalized description of it. The lack of a formalized description, however, did not prevent the widespread use of PL/1 both in Western Europe and in the USSR.

The construction of an extensible language that contains a small core and can be extended to complement the language with data types and operators that reflect the conceptual essence of a specific class of problems. Such a language is called a core language. The languages ​​Simula and Algol-68 were developed as core languages; they were not widely used, but had a great influence on the development of other programming languages.

A further development of the second path was the object-oriented approach to programming, discussed in the next paragraph.

1.2. The essence of the object-oriented approach to programming

The main ideas of the object-oriented approach are based on the following principles:

A program is a model of some real process, part of the real world.

A model of the real world or part of it can be described as a set of objects interacting with each other.

An object is described by a set of parameters, the values ​​of which determine the state of the object, and a set of operations (actions) that the object can perform.

Interaction between objects is carried out by sending special messages from one object to another. A message received by an object may require certain actions to be taken, such as changing the state of the object.

Objects described by the same set of parameters and capable of performing the same set of actions constitute a class of objects of the same type.

From a programming language perspective, a class of objects can be thought of as a type of a datum, and an individual object can be thought of as a datum of that type. The definition by the programmer of his own object classes for a specific set of tasks should allow him to describe individual tasks in terms of the task class itself (with an appropriate choice of type names and object names, their parameters and performed actions).

Thus, the object-oriented approach assumes that when developing a program, the classes of objects used in the program must be determined and their descriptions must be constructed, then instances of the necessary objects must be created and the interaction between them must be defined.

It is often convenient to structure object classes so that they form a hierarchical structure. For example, the class “Student”, which describes an abstract student, can serve as the basis for constructing the classes “1st year student”, “2nd year student”, etc., which have all the properties of a student in general and some additional properties that characterize a student of a specific course. When developing a user interface, programs can use objects of the general “Window” class and objects of classes of special windows, for example, information message windows, data entry windows, etc. In such hierarchical structures, one class can be considered as the base class for other classes derived from it. An object of a derived class has all the properties of the base class and some properties of its own, and it can respond to the same types of messages from other objects as an object of the base class and to messages that are meaningful only to the derived class. It is commonly said that an object of a derived class inherits all the properties of its base class.

Some parameters of an object can be localized inside the object and are not available for direct influence from outside the object. For example, while an object-car is moving, the object-driver can influence only a limited set of controls (steering wheel, gas, clutch and brake pedals, gear lever) and is unable to access a whole range of parameters characterizing the state of the engine and the car as a whole.

Obviously, in order to productively use the object approach for program development, programming languages ​​are needed that support this approach, i.e. allowing you to build a description of object classes, generate data of object types, and perform operations on objects. One of the first such languages ​​was the SmallTalk language, in which all data are objects of certain classes, and the overall class system is built as a hierarchical structure based on predefined base classes.

Programming experience shows that any methodical approach in programming technology should not be applied blindly, ignoring other approaches. This also applies to the object-oriented approach. There are a number typical problems, for which its usefulness is most obvious, such problems include, in particular, simulation modeling tasks and programming dialogues with the user. There are also tasks in which the use object approach will lead to nothing but unnecessary labor costs. In this regard, object-oriented programming languages, which allow combining the object approach with other methodologies, have become most widespread. In some languages ​​and programming systems, the use of the object approach is limited to user interface tools (for example, early versions of Visual FoxPro).

The most commonly used object-oriented languages ​​today are Pascal with objects and C++, with the most advanced tools for working with objects contained in C++.

Almost all object-oriented programming languages ​​are evolving languages; their standards are regularly refined and expanded. The consequence of this development is the inevitable differences in the input languages ​​of the compilers of different programming systems. .The most common programming systems at present are Microsoft C++, Microsoft Visual C++ and programming systems from Borland International. Further material in this manual is presented in relation to the Borland C++ programming system. This is primarily due to the presence in this programming system of a developed integrated environment that combines a text editor, a compiler, a linker (linker) and debugging tools.

2. Basic information about the C language

2.1 Purpose of Xi, historical information

The C language was developed in the 70s as a systems programming language. At the same time, the task was to obtain a language that would ensure the implementation of the ideas of procedural and structured programming and the ability to implement specific techniques of system programming. Such a language would allow the development of complex programs at a level comparable to assembly programming, but much faster. These goals were largely achieved. Most C compilers are written in C, operating UNIX system <также почти полностью написана на Си. Недостатком Си оказалась низкая надежность разрабатываемых программ из-за отсутствия контроля типов. Попытка поправить дело включением в систему программирования Си отдельной программы, контролирующей неявные преобразования типов, решила эту проблему лишь частично.

Based on C, the C++ language was developed in the 80s, initially called “C with classes.” C++ practically includes the C language and is supplemented with object-oriented programming tools. The working version of C++ appeared in 1983. Since then, the language has continued to develop and several versions of the draft C and C++ standards have been published.

A number of software companies have developed compilers for C and C++. Borland International's programming systems stand out among other companies primarily due to their comprehensive approach to program development, which is expressed in the inclusion in the programming system of an integrated developer environment that combines, under common control, a text editor for entering program source codes, a compiler, a link editor and a set of debugging tools. In 1989, this company released the Turbo C++ system, which included a C++ compiler running in the DOS operating system; since 1992, Borland C++ systems have been produced, containing C++ compilers for DOS and WINDOWS; since 1997, the Borland version has been supplied C 5.0, containing C++ compilers for WINDOWS, and the compiler for WINDOWS now allows you to develop both 16-bit and 32-bit versions of programs for PCs with i486 and Pentium processors.

A C/C++ program is one or more source files that can be translated separately. The translation results (object files) are combined into an executable file by the linker (linker). There are generally two types of source files: header files and program files. Header files contain descriptions of data types and function prototypes and are intended to be included in program files before they are compiled; their names typically have a .h extension, such as stdio.h. Program files contain descriptions of functions and, possibly, global variables and constants; their names are usually written with the extensions .c or .cpp, for example, myprog.cpp. The same header file can be included in multiple program files

Each file contains a sequence of so-called "external definitions" that describe data types, variables, constants and functions.

The following paragraphs in this section provide an overview of C/C++ features that are not related to C++ object orientation.

2.2 Alphabet, basic types and description of data.

The language alphabet includes almost all the symbols found on a standard PC keyboard:

Latin letters A...Z, a...z;

Digits 0...9;

Operation signs and separators:

{ } () . , -> & * + - ~ ! / % ? : ; = < > | # ^

Some operations are indicated by combinations of symbols; the meanings of operation symbols in some cases depend on the context in which they are used.

Basic (predefined) data types are combined into two groups: integer data and floating point (real) data.

Integer data can be a regular signed integer or an unsigned integer. Based on the number of bits used to represent a given value (range of values), a distinction is made between regular integers (int), short integers (short int) and long integers (long int). Character data (char) is also treated as an integer and can be signed or unsigned.

Integer type constants are written as sequences of decimal digits, the type of the constant depends on the number of digits in the constant notation and can be specified by adding the letters L or l (long type), U or u (unsigned type) or a combination of them at the end of the constant:

321 - int type constant,

5326u - unsigned int type constant,

45637778 - long int type constant,

2746L - long int type constant.

Integer constants can be written in octal system notation, in this case the first digit must be 0, the number can only contain digits 0 ... 7:

0777 - int type constant,

0453377 - long type constant.

Integer constants can also be written in the hexadecimal number system; in this case, the constant entry begins with the characters 0x or 0X:

0x45F - int type constant,

0xFFFFFFFF - unsigned long type constant.

Constants of type char are always enclosed in single quotes, and the value of the constant is specified either by a character from the character set used or by an integer constant preceded by a backslash: "A", "\33", "\042", "\x1B". There are also a number of special characters that can be specified as char constant values:

"\n" - new line,

"\t" - horizontal tab,

"\v" - vertical tab,

"\r" - carriage return,

"\f" - page feed,

"\a" - sound signal,

"\"" - single quote (apostrophe),

"\"" is a double quote,

"\\" is a backslash.

Real numbers can be one of three types: float, double, long double. The range of values ​​for each of these types depends on the computer and compiler used. Real type constants can be written in natural or exponential forms and are of type double by default, for example, 15.31, 1.43E-3, 2345.1e4. If necessary, the type of a constant can be specified by writing at the end the suffix f or F for the float type, or the suffix l or L for the long double type.

The outer definition declaring variables consists of an optional storage class specifier, type specifiers, and a list of so-called initializer declarators, each of which declares the identifier of one variable and, possibly, the value assigned to the variable when it is declared. The outer definition ends with a semicolon:

int i, j, k; // Three int variables without explicit initialization

double x=1, y=2; //Two double variables with initial values ​​1 and 2

char c1="0"; // Variable of type char, its value is character code 0

The text written after the // signs in these examples is a comment and serves only to document the program. Such a comment can only occupy one line of text and is allowed in C++ program texts. A comment spanning several lines is enclosed in special brackets /* and */.

The external definition can specify one of the keywords extern, static, or typedef as memory class specifiers. The extern specifier means that the declared object belongs to another program file, and here information about its name and type is given and no initialization expression must be present. The static specifier limits the scope of the declared name to a given file or block if the declaration is contained in a block.

If the data declaration is contained within the function body (local declaration), then the register or auto memory class specifiers can be specified. The register specifier is advisory in nature; the compiler tries to place this class in a processor register if there are currently free registers. The auto specifier is the default and therefore not explicitly specified; it means that the auto class must be placed on the software stack when the function is called.

The typedef specifier is used to assign a name to the data type being described and will be discussed in more detail in the next paragraph.

Along with the literal constants shown above, the values ​​of which are determined by their representation in the program, C and C++ provide constants that are assigned their own names - named constants. The description of a named constant contains the const descriptor, for example,

const double Pi = 3.141592653;

A variable whose identifier is declared with a const descriptor cannot be assigned a value other than the one set when declaring the identifier. The initializing value when declaring a constant is required.

Along with basic integer and real types of various sizes, a program can declare and use data of programmer-defined types: pointers, references, data aggregates, and enumerated data.

An enumeration type is used for integer data that can take a limited set of values. Each value has its own identifier name and an integer, the value of this name. The declaration of an enumerated type is constructed according to the following scheme:

enum identifier (enumeration list) declarator-initializers;

Here the identifier specifies the name of the enum type, the enumeration list consists of enumerators separated by commas. Each enumerator is specified by an identifier and possibly an integer value of type char or int, e.g.

enum color (RED, GREEN, BLUE) en_color;

enum lex_type ( CNST, VAR, OPER=3, FUNC );

If an enumerator value is not specified, the first one gets a value of 0, and each subsequent one gets a value greater than 1. In general, any enumerator by default has a value 1 greater than the previous one. In C/C++ it is customary to write enumerator identifiers in capital letters. Enumerator names are used either as named constants or for assignment to variables of an enumerated type.

In C/C++, pointers are used to reference a variable of one type or another. A pointer is a data type whose value is the address of another data. When declaring a pointer, the * sign is written before the identifier. The pointer can be initialized with the address of the given one; the & operation (ampersend) is used to obtain the address:

double *px, *py =

For pointers, comparison operations are defined, adding a pointer to an integer, subtracting two pointers, as well as an indexing operation (operation).

To access a variable by pointer, a dereferencing operation is performed, denoted by * (asterisk), for example, *py = 7.5; .

When declaring a pointer, a const descriptor can be used, for example,

const int cc = 20;

const int *pc = // Can be initialized with the address of a constant.

double *const delta = 0.001; // Pointer - constant

In addition to ordinary variables and pointers, C++ has a “variable reference” type, which specifies an additional name (alias) for the variable. The internal representation of a link is the same as a pointer, i.e. in the form of a variable address, but accessing a variable by reference is written in the same form as accessing it by its base name. A reference type variable is always initialized by specifying the name of the variable to which the reference refers. When declaring a link, the type name is followed by & (ampersend):

With this description, the operators aii = 5; and ii = 5; are equivalent.

Arrays can be formed from variables of any type. When declaring an array in the initializer declarator, the array identifier is followed by the number of array elements in square brackets:

int a [ 5 ] ; // Array of five elements of type int

Array element indices always start at 0, the index of the last element is one less than the number of elements in the array. An array can be initialized with a list of values ​​in curly braces:

int b [ 4 ] = ( 1, 2, 3, 4 );

If you have an initialization list that covers all elements of the array, you do not need to specify the number of array elements; it will be determined by the compiler:

int c = ( 1, 2, 3 ); // Array of three elements of type int

Arrays with a dimension of 2 or more are treated as arrays of arrays and the number of elements is specified for each dimension:

double aa [ 2 ] [ 2 ] = ( 1, 2, 3, 4 ); // Matrix 2 * 2

Arrays of type char can be initialized with a string literal. A string literal is a sequence of any characters other than quotes and backslashes, enclosed in quotes. If a string literal does not fit on one line, it can be interrupted with a "\" character and continued from the beginning of the next line. The C++ standard also provides another way to write long literals in the form of several string literals written in a row. If there are no characters other than spaces between string literals, such literals are merged into one by the compiler.

When placed in memory, the character "\0" is added to the end of the string literal, i.e. null byte. A string literal can also be used to initialize a pointer to a char type:

char str1 [ 11 ] = "This is a string",

str2 = "The size of this array is determined"

"number of characters in literal + 1";

char *pstr = "Pointer with string initialization";

An array name in C/C++ is a constant pointer that refers to the first element of the array, which has an index of zero. To access an array element, specify the array identifier and the element index in parentheses, for example, c, aa.

2.3 Structures and unions

Along with arrays, C/C++ has data aggregates such as structures and unions. A structure type is an ordered collection of data of different types that can be accessed as a single data. The description of the structural type is constructed according to the following scheme:

struct identifier

( member declarators ) declarator_initializers;

Such a declaration performs two functions: firstly, a structure type is declared, and secondly, variables of this type are declared.

The identifier after the struct keyword is the name of the structure type. The type name may be missing, then the type will be nameless and data of this type cannot be declared in other parts of the program. Declarators_initializers declare specific variables of a structure type, i.e. data of the described type, pointers to this type and data arrays. Declarators_initializers may be absent, in which case the declaration describes only the type of the structure.

The structure describing a point on a plane can be defined as follows:

struct Point_struct // Structure name

( int x, y; ) // Declarators of structure members

point1, *ptr_to_point, arpoint ; // Structural type data

The members (components) of a structure are described similarly to the data of the corresponding type and can be scalar data, pointers, arrays, or data of another structure type. For example, to describe the structural type “rectangle with sides parallel to the coordinate axes,” several options can be offered:

(Point p1; // Coordinates of the upper left corner

Point p2; // Coordinates of the lower right corner

(Point p; // Upper left corner

int width; // Width

int high; // Height of the rectangle

Because only previously defined type names must be used when declaring structure members, there is an option to pre-declarate a structure by specifying only the name of the structure type. For example, to describe an element of a binary tree that contains pointers to the left and right branches of the tree and a pointer to some structure of type Value containing the value of the given node, you can do this:

struct Tree_element

Tree_element *left, *right;

Members of structures can be so-called bit fields, when several integer data of a smaller length are placed in the memory field of an integer type variable (int or unsigned int). Let, for example, in some parsing program, the description of a lexeme contains the type of the lexeme (up to six values) and the serial number of the lexeme in the table of the corresponding type (up to 2000 values). To represent a token type value, three binary digits (three bits) are sufficient, and to represent numbers from 0 to 2000, 11 binary digits (11 bits) are required. The description of the structure containing information about the token may look like this:

(unsigned int type_lex: 3;

unsigned int num_lex:11;

A colon with an integer after the structure member name indicates that it is a bit field, and an integer specifies the size of the field in bits.

A union can be defined as a structure whose components are all located in memory from the same address. Thus, the union at each point in time contains one of the possible values. To accommodate a union, an area of ​​memory is allocated that is large enough to accommodate the largest member of the union. Using a union also allows the same memory field to be accessed by different names and interpreted as values ​​of different types.

The description of a union is built according to the same scheme as the description of a structure, but instead of the struct keyword, the word union is used, for example, the union uword allows you to interpret a memory field either as an unsigned int, or as an array of two elements of type unsigned char.

(unsigned int u;

unsigned char b [ 2 ];

Descriptions of types declared by the programmer, including structures and unions, can be quite large, so C/C++ provides the ability to assign proper names (synonyms) to types, thereby increasing the clarity of program texts. A synonym for the type name is entered with keyword typedef and is constructed as a regular declaration, but the identifiers in the declarators in this case are interpreted as synonyms of the described types. Synonyms for type names are usually written in capital letters to distinguish them from variable identifiers. Below are some examples of declaring type name synonyms.

typedef struct ( double re, im ) COMPLEX;

typedef int *PINT;

After such declarations, a name synonym can be used as a type specifier:

COMPLEX ca, *pca; // type variable COMPLEX and pointer to COMPLEX

PINT pi; // pointer to int

The above description of structures and unions basically corresponds to their construction in the C language. In C++, structures and unions are special cases of object data types. More information about this will be given when considering object-oriented C++ tools.

2.4 Operations and expressions

Despite the limited set of basic data types (integer and real arithmetic data and string literals), the C++ language defines an extensive set of operations on data, some of which directly correspond to machine commands. As in all programming languages, operations are used to construct expressions. An expression is a sequence of operands and operation signs and is used to calculate a certain value.

The operands in the expression are variable identifiers, constants, and string literals, which are primary expressions. An expression enclosed in parentheses is also treated as a primary expression. Each operation involves the use of certain types of operands (integer, real, pointers). The assignment operator in C++ is also an expression; therefore, there is a distinction between operands that can be assigned a new value and operands whose value cannot change. In order for an operand to be assigned a value, it must correspond to a memory location and the compiler must know the address of that memory. Such operands are called L-expressions (from English left) because they can be written on the left side of the assignment operator.

The result of evaluating an expression depends on the priorities of the operations. C++ has a complex system of operation priorities, including 16 levels. Table 2.1 shows a list of C++ operations indicating their priorities, purpose and recording scheme.

Table 2.1

A priority

Operation sign

Purpose

Scheme

Accessing a global name or a name from another scope

::identifier (global)
scope name: : structure_member_name

Accessing a structure member by a pointer to the structure

pointer -> structure_member_name

structure_name. structure_member_name

Accessing an array element

index [index]

Data type conversion

type_name (expression) or (type) expression

Calling a function

function(arguments)

Auto-increase

L-value or
L-value++

Auto-reduce

L-value or
L-value--

Bit inversion

~ integer_expression

Logical negation

Expression

Single minus

Expression

Single Plus

Expression

Getting an address

& L-value

Pointer dereference

* pointer

Dynamic memory allocation

new data type

Freeing up memory

delete pointer

Freeing memory for an array

delete pointer

Size of this

sizeof expression

Size type given

sizeof (type name)

Multiplication

expression * expression

expression / expression

Remainder of division by whole

expression % expression

Accessing a structure member by pointer

pointer_to_structure ->* member_name of pointer_structure

Referring to a structure member by structure name

structure_name.*
pointer-structure membername

Addition

expression + expression

Subtraction

expression - expression

Shift left

integer_expression<< целое_выражение

Shift right

integer_expression >> integer_expression

expression< выражение

Less or equal

expression<= выражение

expression > expression

More or equal

expression >= expression

expression == expression

expression != expression

Bitwise conjunction

expression & expression

Denial of equivalence

expression ^ expression

Bitwise disjunction

expression | expression

Logical "AND"

expression && expression

Logical "OR"

expression | | expression

Conditional expression

expression? expression1: expression2

Simple assignment

expression = expression

Compound assignment, @ sign - one of the operator signs * / % + -<< >> & ^ |

expression @= expression

Follow operation

expression, expression

Let's consider the features of using the main operations listed above.

The operation ": :" (two colons) is used to clarify the name of a program object in the case when two identical names are known at this place in the program, for example, when one name is declared globally and the other in the body of a function. If the name is preceded by two colons, then it is a global name.

To access the members of a structure or union, you can use either the name of the structure data or a pointer to the structure data. In the first case, the full name of a structure member consists of the name of the structure itself and the name of the structure member, separated by a dot. In the second case, the name of the pointer to the structure is followed by a -> sign (arrow), followed by the name of the structure member. Let a program declare a structural type AnyStruct containing a component named member of type int and declared

AnyStruct s1; // Data s1 of type AnyStruct

AnyStruct *ps1 = // Pointer to a data of type AnyStruct

Then the member of the structure member from s1 can be accessed as s1.member or as ps1->member.

Since a member of a structure can be a pointer, C++ has special operations for dereferencing such a pointer, the operations .* and ->. Let one of the members of the AnyStruct structure be a pointer pp1 to a data of type int. Then the expressions s1.*pp1 and ps1->*pp1 will provide access to the datum value pointed to by pp1 from s1.

It was noted above that the name of an array in C/C++ is interpreted as a constant pointer to the first element of the array. To dereference a pointer, i.e. To access a given by a pointer to this given, use the * (asterisk) operation. Therefore, if the program declares an array

int Array1[10];

then the expression *Array1=0 is used to assign a zero value to the first element of the array. To access an arbitrary array element, you need to specify the index of the element, for example, Array1. This expression is equivalent to *(Array1 + 3), i.e. you first need to increment the Array1 pointer by 3 units, and then dereference the resulting pointer. When adding a pointer to an object of some type T with an integer N, the value of the pointer is increased by N multiplied by the length of this type T. Note that the index can be set not only for array names, but also for any pointer type, except for a pointer to a void type:

int *pint = &Array[ 4 ]; pint [ 2 ] =1;

In this example, the pint pointer is initialized to the address of the fifth element of the Array, and then the seventh element of that array is assigned the value 1.

The index can be any expression with a value of integer type.

Since C++ is a typed language, it defines explicit and implicit data type conversions. Implicit conversions are performed on double arithmetic and assignment operations and are called standard arithmetic conversions. These transformations are performed in the following sequence:

If one operand is a long double, the other operand is converted to a long double;

Otherwise, if one operand is of type double, the other operand is converted to type double;

Otherwise, if one operand is of type float, the other operand is converted to float;

Otherwise, if one operand is of type unsigned long int, the other operand is converted to type unsigned long int;

Otherwise, if one operand is of type long int, >the other operand is converted to type long int;

Otherwise, the standard conversions for integers are performed, with char, short int and bit fields of type int being converted to type int, then if one operand has a larger size (larger range of values) than the other operand, then the second operand is converted to the type of the operand bigger size;

In other cases, the operands are of type int.

Explicit type conversion can be specified in two forms. The first form is C-compatible and follows the type name in parentheses with the value to be converted, which can be a primary expression or an expression with a one-place operator. The type name in this case can be represented by a sequence of descriptors, for example, (long int *) pp specifies the conversion of some given pp to a pointer type to long int. The second form of type conversion is written as a function call, where the type name must be specified by an identifier, such as int(x). It should be noted that the result of an explicit conversion is not an L-value.

The autoincrement and autodecrement operations (++ and --) can be prefix or postfix and cause an increase (decrease) of its operand by one, i.e. the expression ++x is equivalent to x = x +1, and --x is equivalent to x = x - 1. A prefix operation is performed before its operand is used in evaluating the expression, and a postfix operation is performed after its operand is used in expression, for example, as a result of evaluating the expression

X * 2 + y-- *3

the variable x is first increased by 1 and then multiplied by 2, the variable y is first multiplied by 3, then decreased by 1. If before evaluating this expression x and y were equal to 1, then the result of the expression will be equal to 5, in addition, the variable x will receive the value 2, and the variable y is the value 0. Thus, the autoincrement and autodecrement operations always have the side effect of changing the values ​​of their operands. The operands of these operations must be L-values.

The ~ (tilde) operator applies only to an integer value and replaces all bits of its operand with a value of 0 to 1, and bits with a value of 1 to 0.

Logical negation (operation!) returns the value 0 of an integer type if the operand is not zero, or the value 1 if the operand is zero.

The operations “single +” and “single -” have the usual mathematical meaning, the + sign does not change the value of the operand, the - sign changes the sign of the operand to the opposite.

To obtain the address of the operand, which is an L-value, the & (ampersand) operator is used. The result of this operation will be a pointer to the corresponding data type. Pointer dereferencing, i.e. obtaining a given value from a pointer to it is ensured by the * (asterisk) operation. The result of the dereference operation is the L-value.

C++ defines operations for placing data in dynamic memory and removing dynamic data from memory.

The new operation requires a type name as an operand and is intended to place the given specified type in dynamic memory; the result of the operation will be a pointer to the given one. If it is impossible to allocate memory, the new operation returns the value NULL - a predefined constant that has a zero value in almost all C and C++ compilers. The memory allocated by the new operation can be initialized by specifying an initial value in parentheses after the scalar data type name; setting initial values ​​for data aggregates will be discussed later. Examples of using the new operation:

int *ip = new int; /* creating an object of type int and getting a pointer to it */

int *ip2 = new int(2); // the same with setting the initial value to 2

inr *intArray = new int [ 10 ]; // array of 10 elements of type int

double **matr = new double [ m ] [ n ]; // matrix of m rows and n columns

Data placed in dynamic memory by the new operation is deleted from memory by the delete operation with a pointer operand whose value is obtained by the new operation, for example,

delete intArray; delete ip2;

The delete operation only frees dynamic memory, but does not change the value of the pointer operand. The programmer must remember that after freeing the memory, this pointer cannot be used to access the data.

The size of a given or given type in bytes can be obtained using the sizeof operation. The operand can be of any type except function type and bit field. If the operand is a type name, it must be enclosed in parentheses. The return value has a predefined type size_t, this is an integer type whose size is determined by the compiler implementation, usually the type size_t corresponds to unsigned int. The size of the array is equal to the number of bytes occupied by the array in memory, the size of a string literal is the number of characters in the literal +1, i.e. the terminating null byte is taken into account when determining the length of the literal. The value returned by sizeof is a constant.

The double arithmetic operations of multiplication (*), division (/), remainder of integer division (%), addition (+) and subtraction (-) have the usual meaning and the usual relative priority. If the operands of an arithmetic operation have different types, standard arithmetic conversions are performed first, and the type of the result of the operation is determined by the general type of the operands after the standard conversions. Therefore, the expression 7/2 will result in 3 ints since both operands are of type int, and the expression 7.0/2 will result in 3.5 doubles since the first operand is of type.

Operations of the relation of two expressions (<, <=, >, >=) require operands of arithmetic type, or both operands must be pointers to the same type. For arithmetic type operands, the values ​​of the operands are evaluated, standard arithmetic conversions are performed, and an int of type 1 is returned if the relation holds (true) or 0 if the relation does not hold (false). When two pointers are compared, the result depends on the relative memory placement of the objects referenced by the pointers. Comparison operations (== and !=) are performed in a similar way, but have lower priority.

Relational expressions can be connected by logical connectives && (conjunction, logical multiplication) and | | (disjunction, logical addition). In general, the operands of logical connectives can be any scalar values, and the && operation gives a result equal to 1 of type int if both operands have non-zero values, and the | | gives a result of 0 if both operands are zero. A shortened form of calculating the value of logical connectives is used: if in the && operation the first operand is zero, then the second operand is not calculated and 0 is returned, if in the | | The first operand is not zero, then the second operand is not evaluated and the value 1 is returned.

As already noted, assignment, denoted by the = sign in C/C++, is treated as an operation and returns the value that was assigned to the left operand. The assignment operation is evaluated from right to left, i.e. first the value to be assigned is calculated, then the assignment is performed. This allows you to write expressions like x = y = z = 1 to set multiple variables to the same value. It is possible, although this reduces the clarity of the program, to construct expressions with side effects of the form (x = 2) * (y = 3) + (z = 4). The result of this expression will be 24, but at the same time the variables x, y and z will receive new values.

In addition to simple assignment, there is a set of compound assignment operations in which an assignment is combined with a specified double operator. Writing x += y is equivalent to x = x + y.

Left and right shift operations are defined for integer operands. When performing operation e1<< e2 биты первого операнда сдвигаются влево на e1 разрядов и результат имеет тип первого операнда. Освобождающиеся правые разряды заполняются нулями. При сдвиге вправо (e1 >> e2) if e1 is of type unsigned, the vacated left bits are filled with zeros, and if e1 is of type signed, the signed bit is repeated in the vacated left bits.

The operations of bitwise logical multiplication, logical addition and exclusive or (negation of equivalence) are allowed over integer operands. In these operations, the operands are treated as sequences of bits and the operation is performed on each pair of corresponding bits from both operands. For example, the result of the expression (x >> (p - n +1)) & (~(~0<< n)) будет выделение из целого беззнакового x n битов, начиная с бита с номером p, и сдвиг выделенных битов вправо, т.е. выделение n-разрядного целого, хранящегося в машинном слове x начиная с p-го разряда.

C/C++ has a construct called a conditional expression. The conditional expression is constructed according to the following scheme:

condition? expression1: expression2

The condition can be any scalar expression. If the result of calculating the condition is non-zero, then the value of the entire expression will be expression1; if the condition is zero, the value of the entire expression is determined by expression2. The second and third operands of the conditional expression must either be both arithmetic types, or structures or unions of the same type, or pointers of the same type, or one of them is a pointer to some type and the other operand is NULL or has type void*. Expression x > 0 ? 1:0 returns 1 if x is greater than 0, and 0 otherwise.

An expression can be represented as a sequence of expressions separated by commas, in which case all expressions are evaluated from left to right and the value of the last expression in the list is returned. For example, as a result of evaluating the expression

x = 2, e * 3, x +1 the value 3 will be obtained and at the same time x will receive the value 2. The result of multiplying e * 3 cannot be used in any way.

2.5 C++ operators

Operators are syntactic constructs that define the actions performed by a program. The following types of operators are available in C/C++: expression operators, selection operators, loop operators, and jump operators. The syntax of some operators contains expressions that play the role of conditions, depending on the fulfillment or non-fulfillment of which a particular sequence of actions is selected. Since there are no Boolean expressions in C, any expression that evaluates to a scalar value is used as conditions, and the condition is satisfied if the value is nonzero and fails if it is zero. Multiple statements can be combined into a compound statement by enclosing them in curly (operator) braces. End-of-statement marker (except compound operator) is a semicolon, which in this case is part of the operator.

Any operator can be preceded by a label in the form of an identifier separated from the operator being marked by a colon. The label serves only to indicate it in the jump statement.

The simplest is the expression operator, which is a complete expression ending with a semicolon, for example,

x = 3; y = (x +1) * t; i++;

An expression written as an operator is evaluated, but its value is lost and the effect of the expression operator is the side effects that accompany the evaluation, for example, when performing assignment, autoincrement, and autodecrement operations.

Selection operators in C/C++ are represented by a conditional operator and a switch. The conditional statement is similar to conditional statements in other programming languages ​​and can be used in shorthand and full forms, which correspond to the schemes:

if (conditional expression) statement

if (conditional expression) statement-1 else statement-2

In the short form of the conditional operator, the condition expression is evaluated and, if its value is non-zero, the statement following the condition is executed, otherwise no action is taken.

Similar documents

    Analysis of object-oriented programming that simulates the way things are done. Basic principles of object-oriented programming: encapsulation, inheritance, polymorphism. The concept of classes, fields, methods, messages, events.

    test, added 01/22/2013

    Using a scripting programming language to develop web applications (scripts). Learn the fundamentals of object-oriented programming in PHP language. Familiarization with special methods for working with classes. Purpose of interfaces.

    test, added 03/14/2015

    General characteristics of the object-oriented approach in programming, its main properties and principles. Development of a program for automation of cafe activities based on an object-oriented approach, design and implementation of a data schema.

    course work, added 01/22/2012

    Characteristics and properties of programming languages. Study of the evolution of object-oriented programming languages. Construction of an evolutionary map of OOP mechanisms. Development conceptual model functioning of the user interface.

    course work, added 11/17/2014

    Using Object Oriented Programming - good decision when developing large software projects. Object and class as the basis of an object-oriented language. The concept of object-oriented languages. Languages ​​and software environments.

    test, added 01/17/2011

    Study of the principles of object-oriented programming, in which the main concepts are the concepts of classes and objects. Properties of this type of programming: encapsulation, polymorphism, inheritance. Description of the class. Constructors and destructors.

    presentation, added 10/14/2013

    Creation of software - a simulation modeling system on the topic "Production line with technical control points." Description of input and output data. Object-oriented programming. Diagrams of modules and processes.

    course work, added 01/09/2014

    Properties of an object-oriented programming language. Concepts of encapsulation and inheritance. Virtual functions and polymorphism. Initializing an object instance using a constructor. Dynamic creation objects. Object type compatibility.

    abstract, added 04/15/2015

    The concept of an algorithm and its characteristics as a basic element of programming. Forms of presentation of algorithms, basic algorithmic structures. Structured and event-oriented programming. Object-oriented programming.

    abstract, added 07/17/2008

    Developing a program using the principles of object-oriented programming in the language high level With Microsoft Visual Studio 2010 tools. Construction of an implementation algorithm. Program class, instructions for using the program.

Ufa State Aviation Technical University

Department of Computer Engineering

and Information Protection

Explanatory note

for course work

in the discipline: “Programming methods and applied algorithms”

“Development of an applied algorithm and its implementation in C++”

Is done by a student:

Zaguraev A.N.

Faculty: IRT

Group: ZI-225

Accepted by Associate Professor, Ph.D.:

Strokina Yu.G.

1. Statement of the problem…………………………………………………………….……3

2. Borland C++ Builder programming environment…………………..4

3. Mathematical software…………………………….…………10

4. Development of a program algorithm in the form of a block diagram…….……11

5. Description of the program………….…………………………….12

6. Conclusions………………………………….…………………………….15

7. List of references…….………………………….16

Appendix………………….……………………………..……………..17

Formulation of the problem

Exercise: Develop a program for iterative search for the size of uniform loan payments. Payments and interest accrual on the remaining amount are made monthly. Initial data: loan size, repayment period (from 1 to 5 years), interest rate. In the dialog box, display a graph of changes in the balance of the loan amount.

Programming environmentBorlandC++ Builder

Introduction

Borland C++ Builder is a rapid application development environment. Rapid development systems (RAD systems, Rapid Application Development - an environment for rapid application development) are based on the technology of visual design and event programming, the essence of which is that the development environment takes on most of the work of generating program code, leaving the work to the programmer on designing dialog boxes and writing event processing functions. Programmer productivity when using RAD systems increases significantly.

The Borland C++ Builder object-oriented programming system is designed for Windows operating systems. The C++ Builder IDE provides the speed of visual development, the productivity of reusable components, combined with the power of C++ language tools, advanced tools, and multi-scale database access.

C++ Builder can be used wherever you want to extend existing applications with the advanced C++ language standard, improve performance, and give a professional-grade user interface.

Visual development speed

Professional C++ language tools are integrated into the visual development environment. C++Builder provides a fast Borland C++ compiler, an efficient incremental loader, and flexible debugging capabilities at both the source and assembly level to meet the demanding demands of professional programmers.

Drag-and-drop design allows you to create an application by simply dragging captured visual components from the Palette onto the application form. The object inspector provides the ability to operate with the properties and events of components, automatically creating templates for event processing functions that are filled with code and edited during the development process.

Properties, methods and events are precisely those language elements that enable rapid application development within the framework of object-oriented programming. “Properties” allow you to easily set various characteristics of objects. “Methods” perform certain, sometimes quite complex, operations on an object. “Events” connect user impacts on objects with response codes to these impacts. Events can occur during such specific changes in the state of objects as updating data in interface elements for accessing databases. Working together, properties, methods, and events form a RAD (Rapid Application Development) environment for quickly and intuitively programming robust Windows applications.

Visual Shape Inheritance embodies a critical aspect of object-oriented programming in an easy-to-use visual design tool. The characteristics of a new application form can be inherited from any other existing form, which provides centralized reproduction of user interface changes, facilitates code control, and reduces the time required to introduce new quality attributes.

The installation wizard guides the creation of unified distribution packages for developed applications.

The source code of the Visual Component Library facilitates the development of new components based on ready-made examples.

Open API tools can be directly integrated into the visual environment of the system. You can connect your usual text editor or create your own wizard to automate repetitive procedures.

The expanded mathematical library contains additional unified functions for statistical and financial calculations.

InterfaceBorlandC++ Builder.

The C++ Builder interface includes:

Palette components contains more than 100 reusable components offered for building applications.

Form editor designed to create a program interface with the user.

Editor code is intended for writing program text, in particular, event processing functions.

Object Inspector allows you to visually set the properties of objects without the need for routine programming and contains events that can be associated with object reaction codes to their occurrence.

Object storage contains objects such as forms and data modules that are shared among many applications to reduce development time.

C++Builder implements a visual method for building applications by selecting the necessary control elements from the Component Palette (Fig. 1). Each component (such as a button) has properties associated with it that change its appearance and behavior. Any component can trigger a series of events that determine its response to various influences.

Compatibility issues

C++ Builder brings the power and richness of the C++ language to the entire family of object-oriented programming systems. C++ Builder can be used wherever you want to enhance existing applications with advanced industry standard C++, improve performance, and create a professional-looking user interface.

C++BuilderAndBorland C++

There is complete and mutual interoperability between the C++ Builder and Borland C++ software products. C++ Builder adds a new quality to the programming process - fast visual development of applications in the C++ language. If you are used to working in Borland C++ programming systems (versions 3.1, 4.5 and 5.0), then neither moving to a new system nor returning to the old one will be too difficult. A convenient project file administrator, compiler and incremental loader remain at your disposal.

At first, C++ Builder will disappoint many developers because, instead of the familiar OWL and MFC libraries, it uses the hitherto unknown VCL library. Each library represents a specific object-oriented programming model for Windows. Each library solves OOP problems in its own way, and it cannot be said that any one copes with the task better or worse than others. Borland C++ versions 5.0 and higher support the introduction of standard forms designed in the C++ environment into previously developed OWL or MFC programs Builder based on VCL. The developer goes for this kind of rework for a simple reason: C++Builder allows you to include all dialogs with the user in the form extremely quickly, giving the Windows application a complete professional look, eliminating all the husk of auxiliary code from the program and leaving only the meaningful part that embodies the main algorithm idea. Thus, compatibility is ensured at the form level. Not surprisingly, working together with two object class libraries significantly increases the size of the EXE file.







2024 gtavrl.ru.