Главная » Просмотр файлов » Wiley.Developing.Software.for.Symbian.OS.2nd.Edition.Dec.2007

Wiley.Developing.Software.for.Symbian.OS.2nd.Edition.Dec.2007 (779887), страница 21

Файл №779887 Wiley.Developing.Software.for.Symbian.OS.2nd.Edition.Dec.2007 (Symbian Books) 21 страницаWiley.Developing.Software.for.Symbian.OS.2nd.Edition.Dec.2007 (779887) страница 212018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 21)

To improvecode readability, Symbian OS has a convention of prefixing class names96SYMBIAN OS PROGRAMMING BASICSwith a letter to identify the class type. This convention should be followedwhen creating your own classes that fall into these categories:•T – Data type classes.•C – Heap allocated classes derived from CBase.• R – Resource classes.• M – Interface classes (‘mixins’).4.4.1 Data Type Classes: T classesData type classes (‘T classes’) encapsulate one or more types, usually builtin types (like TInt, TText) or other T classes. T classes have optionalmethods for manipulating, comparing, and otherwise controlling thetype(s) they contain.

The TChar class described in the previous section isa good example of a T class: each instantiation of TChar holds a charactervalue. The TChar class methods can be used to perform operations onthat value.Note that it’s important that a T class not contain any data that requiresdestruction, so do not own heap-based objects or resource handles.

Tclasses do not have destructors.Data type classes start with T, but this convention is not limited toclasses. As we have seen in the previous section, a T is prefixed to anydeclaration that represents a data type. This includes typedefs and enums.4.4.2Heap Classes: C classesHeap classes inherit from Symbian’s CBase class, which is why the Cprefix is used. As the name suggests, they are instantiated on the heap(i.e., with new) as opposed to on the stack as automatic variables or asclass members. Heap classes are referenced by pointers.Deriving a class from CBase ensures that:•The destructor of the derived class is called when the object is deletedthrough a base class pointer.

(CBase declares a virtual destructor.)•All data members in the class are initialized to zero when instantiated.This prevents problems such as uninitialized pointers.Classes of this type should never be allocated on the stack. The zeroinitialization is done by CBase as a result of the new operator, and sincenew is not performed for stack instantiation, the member variables willcontain undefined data when instantiated on the stack (as is normal withnon-CBase-derived classes). This can cause a problem if the class (orclass user) is written to assume that the data is initialized to zero – anSYMBIAN OS CLASSES97assumption that is valid for correctly instantiated Symbian OS heapclasses.4.4.3 Resource Classes: R classesResource classes are used to control objects that are implemented andowned somewhere else.

For example, client classes in a client–serverstructure are implemented as resource classes that just hold a handleto the actual resource, which is controlled by the server. Furthermore,the Symbian OS API provides numerous resource classes that allow userprograms to control objects that are owned and implemented by thekernel (threads, processes, mutexes, and memory chunks are examples ofthis).Resource classes begin with R, which stands for resource (you canalso think of the R as standing for remote).

These classes are normallyallocated on the stack or as class member variables – although they canalso be created on the heap.Since an R class instance is a handle to a resource, deleting it does notdelete the actual resource itself. This is different from the behavior of Tclasses, where deleting a T class instance also deletes the data the T classinstance represents (since the data is just a member of the class).The Symbian RFile API class is a good example of a resource class.Files are opened by instantiating an RFile object and calling its Open()method.

The object then acts as a handle to read and write the file (usingthe Read() and Write() methods of RFile). Deleting the RFileobject does not delete the file associated with it – and the resource mustbe released explicitly by calling Close().Another example is RThread, as illustrated below. (The class RThreadwill be covered in more detail in Chapter 9.)void Func1(){RThread thread;// opens reference to thread with id ThreadXIdthread.Open(ThreadXId);// Raise priority one notch above the default prioritythread.SetPriority(EPriorityMore)thread.Close();}The code in this example will raise the priority of the thread whosethread ID is ThreadXId.

Although RThread’s Close() method iscalled – and the RThread object itself is destroyed when the functionexits – the actual thread is not deleted, since RThread is simply a handleto it. Note that, for simplicity, no error checking is done in this example.RSocket, RProcess, and RSemaphore are other examples ofresource classes.98SYMBIAN OS PROGRAMMING BASICSResource classes follow certain patterns.

They usually use an Open()method (and sometimes Connect()) to create a handle to the resource,and a Close() to close the handle to the resource. Creating and closinga resource handle results in a reference count being incremented anddecremented, respectively, and the Symbian OS kernel will not allow theactual resource to be deleted if there are any open handles to it. For someresources, the resource is deleted automatically by the system when thelast handle to it is closed.4.4.4 Interface Classes: M classesInterface classes, which are prefixed with M for mixin, are abstract classeswhose purpose is to define an interface (sometimes known as a protocol )for other classes to use, as opposed to implementing functionality themselves.

Interface classes have no member variables and in most casescontain only pure virtual functions. Typically, you derive a class from oneor more interface classes using multiple inheritance, and then overrideand implement the interface’s functions as appropriate for your class. Forexample:class MInterface1{virtual void DoThis()=0;};class MInterface2{virtual void Callback()=0;};class CMyClass: public CBase, MInterface1, MInterface2{virtual void DoThis();// override method from MInterface1virtual void Callback(); // override method from MInterface2};void CMyClass::DoThis(){//implementation here}void CMyClass::Callback(){// implementation here}This example shows two interface classes, MInterface1 andMInterface2, each consisting of a single abstract function. ClassCMyClass uses multiple inheritance to inherit from CBase, and from thetwo interface classes.

CMyClass then implements the actual functionalitybehind the interfaces by overriding the interface functions.SYMBIAN OS CLASSES99Having separate classes for interfaces is more manageable than simplyadding all the interface methods directly to your class (or in one of yourbase classes). Furthermore, inheriting from interface classes allows you touse an interface class pointer when operating on an object and not carewhat the actual derived class type of the object is (this is a typical C++polymorphism). For example:void CallMeBack(MInterface2 *aObj){// aObj is assumed to be a valid pointer hereaObj->Callback();}An object of any class type that inherits from MInterface2 can bepassed to CallMeBack() and the appropriate Callback() implementation of the passed object is called.Deriving from interface classes is the only situation in Symbian OSwhere multiple inheritance is encouraged.

You will run into problems ifyou attempt to use other forms of multiple inheritance, since the standardbase classes were not designed to support them.Figure 4.1 provides an example interface class relationship.In Figure 4.1, CClass2 implements two interface classes, MProtocol1 and MProtocol2. CClass1 implements MProtocol1 only. Bothclasses, as is typical, also inherit from a normal, concrete class in additionto the interfaces they implement.Function1(MProtocol1 aProt1) will accept an argument of typeCClass1 or CClass2 since both of these classes are derived fromMProtocol1. The argument is cast down to an MProtocol1 type andFunction1() will then manipulate the object as needed through theMProtocol1 interface methods.Function2(MProtocol2 aProt2) will accept objects of typeCClass2 since CClass2 inherits from MProtocol2.

Passing CClass1to this function will generate a compiler error since CClass1 doesnot inherit from class MProtocol2 (in other words, Class1 does notsupport the MProtocol2 protocol).From an object-oriented point of view, there are many benefits ofusing interface classes for the purpose of managing objects using specificprotocols. While I did not go into the theory in much detail here, hopefullythis gives you a better idea of what interface classes are and how theyare used.If you are a Java programmer, you may recognize the mixin classconcept as being a C++ implementation of the Java interface keyword.CBaseprotocol 2 purevirtual methodsprotocol 1 purevirtual methodsCBaseMProtocol1 methodsimplementationCBaseMProtocol1 methodsimplementationFigure 4.1Interface Classes ExampleMProtocol2 methodsimplementationCClass2 : public CBase, publicMProtocol1, public MProtocol2CBaseMProtocol 2MProtocol1CClass1 : public CBase, publicMProtocol1Function 1(MProtocol1* aProt1){/* Manipulate object throughMProtocol1 methods */}Function 2(MProtocol2* aProt2){/* Manipulate object throughMProtocol2 methods */}100SYMBIAN OS PROGRAMMING BASICSEXCEPTION ERROR HANDLING AND CLEANUP1014.5 Exception Error Handling and CleanupGood error handling and recovery are essential for limited resourcedevices such as smartphones.

For example, if an application runs out ofmemory, the user should not lose any data and the smartphone shouldnot crash.Symbian OS provides an extensive error handling and recovery mechanism that is used heavily in Symbian OS software. You’ll need tounderstand this functionality, since it will comprise a significant portionof your application design and development effort. This section describesit in more detail.4.5.1 Error Handling via Return CodesTraditionally, functions are written to return status codes that indicateeither success or some particular failure. Symbian OS uses this methodfor many of its APIs – a function returns KErrNone on success, and aparticular error code (e.g., KErrNotFound, KErrNoMemory) on failure,as defined in e32std.h. A simple if statement, after the function call,can test for and handle an error.But providing a return status alone is not enough for a robust userexperience.

Why? Two reasons: firstly, not all return codes are tested bythe programmer when invoking functions or creating objects; secondly,the calling function may not know how to handle particular errors, whichcan result in inconsistent behavior for ‘core’ error conditions, such asrunning out of memory.4.5.2 Leaves and TRAP HarnessesTo solve the problems just mentioned, Symbian OS provides an exceptionbased error handling and recovery mechanism based on leaves and trapharnesses. When an error occurs, the software invokes a leave, whichcauses the function to exit immediately.

Характеристики

Тип файла
PDF-файл
Размер
3,36 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
А знаете ли Вы, что из года в год задания практически не меняются? Математика, преподаваемая в учебных заведениях, никак не менялась минимум 30 лет. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6447
Авторов
на СтудИзбе
306
Средний доход
с одного платного файла
Обучение Подробнее