Форум программистов, компьютерный форум, киберфорум
Objective-C
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.75/40: Рейтинг темы: голосов - 40, средняя оценка - 4.75
0 / 0 / 0
Регистрация: 11.08.2014
Сообщений: 40
1

Отличия С++ от objC

14.09.2014, 12:34. Показов 7548. Ответов 9
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Я неплохо знаю С++, закончил пару книг, а также начинал изучать С#, но в один момент, моя жизнь перевернулась и я должен выучить ObjC. Будут-ли у меня сложности с изучением этого языка, то есть переход с С++ будет для меня болезненным?

Я не могу найти в интернете отличия С++ от objC, был бы очень признателен тем, кто все-таки это сделает или сам подскажет.
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
14.09.2014, 12:34
Ответы с готовыми решениями:

IDE для ObjC
Всем привет. Я являюсь владельцем windows. Хотел начать изучать ObjC. Для начала хотел узнать где...

Конвертер из swift в ObjC
Уважаемые коллеги Не может ли кто-то из вас подсказать, существует ли "в природе" опенсорсный...

ObjC как обертка для C?
Доброго времени суток. Я не iOS/MacOS разработчик, мне нет дела до Xcode и яблочного API. Мне...

В проекте нет доступа из Swift к pod библиотеке на ObjC
перепробовал все мануалы и гайды гуру ios dev помогите проект прилагаю спасибо

9
112 / 103 / 12
Регистрация: 01.05.2013
Сообщений: 603
14.09.2014, 16:16 2
отличия С++ от objC
ARC или автоматический счетчик ссылок. Который является "сборщиком мусора" в Objc и удаляет объекты NSObject если на них ничто не ссылается.

В остальном СИ синтаксис, обилие квадратных скобок и избыточный синтаксис в объявлении методов.
Ничего особенного.
1
0 / 0 / 0
Регистрация: 11.08.2014
Сообщений: 40
14.09.2014, 17:15  [ТС] 3
То есть мне будет удобно и быстро перейти на него?
0
686 / 613 / 43
Регистрация: 13.01.2011
Сообщений: 1,722
14.09.2014, 18:39 4
Unifan, не слушайте noname_club.
Он не понимает что такое "сборщик мусора". И не отличает ARC от него.

Попробуйте глянуть на короткий список ключевых отличий
Для меня основная разница - в синтаксисе.
1
112 / 103 / 12
Регистрация: 01.05.2013
Сообщений: 603
14.09.2014, 19:45 5
C++ allows multiple inheritance, Objective-C doesn't.
Unlike C++, Objective-C allows method parameters to be named and the method signature includes only the names and types of the parameters and return type (see bbum's and Chuck's comments below). In comparison, a C++ member function signature contains the function name as well as just the types of the parameters/return (without their names).
C++ uses bool, true and false, Objective-C uses BOOL, YES and NO.
C++ uses void* and NULL, Objective-C prefers id and nil.
Objective-C uses "selectors" (which have type SEL) as an approximate equivalent to function pointers.
Objective-C uses a messaging paradigm (a la Smalltalk) where you can send "messages" to objects through methods/selectors.
Objective-C will happily let you send a message to nil, unlike C++ which will crash if you try to call a member function of NULL
Objective-C allows for dynamic dispatch, allowing the class responding to a message to be determined at runtime, unlike C++ where the object a method is invoked upon must be known at compile time (see wilhelmtell's comment below). This is related to the previous point.
Objective-C allows autogeneration of accessors for member variables using "properties".
Objective-C allows assigning to self, and allows class initialisers (similar to constructors) to return a completely different class if desired. Contrast to C++, where if you create a new instance of a class (either implicitly on the stack, or explicitly through new) it is guaranteed to be of the type you originally specified.
Similarly, in Objective-C other classes may also dynamically alter a target class at runtime to intercept method calls.
Objective-C lacks the namespace feature of C++.
Objective-C lacks an equivalent to C++ references.
Objective-C lacks templates, preferring (for example) to instead allow weak typing in containers.
Objective-C doesn't allow implicit method overloading, but C++ does. That is, in C++ int foo (void) and int foo (int) define an implicit overload of the method foo, but to achieve the same in Objective-C requires the explicit overloads - (int) foo and - (int) fooint) intParam. This is due to Objective-C's named parameters being functionally equivalent to C++'s name mangling.
Objective-C will happily allow a method and a variable to share the same name, unlike C++ which will typically have fits. I imagine this is something to do with Objective-C using selectors instead of function pointers, and thus method names not actually having a "value".
Objective-C doesn't allow objects to be created on the stack - all objects must be allocated from the heap (either explicitly with an alloc message, or implicitly in an appropriate factory method).
Like C++, Objective-C has both structs and classes. However, where in C++ they are treated as almost exactly the same, in Objective-C they are treated wildly differently - you can create structs on the stack, for instance.
по порядку.

1) C++ allows multiple inheritance, Objective-C doesn't.
Множественное наследование достаточно спорный паттерн.
В Objective-C есть интерфейсы (протоколы @protocol).

2) Unlike C++, Objective-C allows method parameters to be named and the method signature includes only the names and types of the parameters and return type (see bbum's and Chuck's comments below). In comparison, a C++ member function signature contains the function name as well as just the types of the parameters/return (without their names).
ну тут в 2 словах если. То речь идет как раз про избыточный синтаксис Objc. В том плане что параметры методов имеют названия, кроме непосредственно имени переменной параметра.

Objective-C
1
[self.helloMethod: param1 withParam2: param2 AndParam3: param3]
3) C++ uses bool, true and false, Objective-C uses BOOL, YES and NO.
C++ uses void* and NULL, Objective-C prefers id and nil.
ну это просто как будет удобно. И то и другое верно.

4) Objective-C uses "selectors" (which have type SEL) as an approximate equivalent to function pointers.
Objective-C uses a messaging paradigm (a la Smalltalk) where you can send "messages" to objects through methods/selectors.
Objc можно совершенно внезапно проверить и вызвать любой метод у объекта. Даже из private секции.

Objective-C
1
2
3
4
5
if ([self respondsToSelector: @selector(helloMethod:)]) {
    // метод helloMethod есть у объекта self
    // вызываем селектор
    [self peformSelector: @selector(helloMethod:) withObject: @"value"];
}
Хотя данная конструкция применятся в качестве вызова метода при паттерне "делегирование", но ничто не мешать вызвать методы которые не видны.

5) Objective-C will happily let you send a message to nil, unlike C++ which will crash if you try to call a member function of NULL
При вызове методов у NIL указателей ошибки не будет. То есть если указатель пуст, то "случаный" вызов у него методов того или иного класса критических ошибок не вызывает.

Однако при работе с массивами и словарями, хранение в них nil недопустимо и вызывает исключение. Вместо этого надо использовать [NSNull null]

6) Objective-C allows for dynamic dispatch, allowing the class responding to a message to be determined at runtime, unlike C++ where the object a method is invoked upon must be known at compile time (see wilhelmtell's comment below). This is related to the previous point.
Objc имеет мощные инструменты для распаралеривания.
Сюда можно отнести класс dispatch* функций, для создания и сихронизации потоков.
И также очереди задач в лице NSOperationQueue
И Также легкое создание блоковых ^{ } конструкций. Внутри других функций.

7) Objective-C allows autogeneration of accessors for member variables using "properties".
Не так давно (ориентировочно IOS5) Objective-C позволяет не использовать вообще слово @synthesize, которое раньше использовалось для объявления свойств у объектов. Теперь достаточно написать 1 слово @property остальное компилятор сделает сам.

8) Objective-C allows assigning to self, and allows class initialisers (similar to constructors) to return a completely different class if desired. Contrast to C++, where if you create a new instance of a class (either implicitly on the stack, or explicitly through new) it is guaranteed to be of the type you originally specified.
Objc контрукторы классов всегла возвращают тот класс который создается. В отличие от C++ где есть хаки для создания конструктора который не будет возвращать верный класс.

9)Objective-C lacks the namespace feature of C++.
Objective-C lacks an equivalent to C++ references.
Objective-C lacks templates, preferring (for example) to instead allow weak typing in containers.
В Objective-C нет:
- шаблонов
- пространств имен (namespace)
- типов данных присущих C++

10)Objective-C doesn't allow implicit method overloading, but C++ does. That is, in C++ int foo (void) and int foo (int) define an implicit overload of the method foo, but to achieve the same in Objective-C requires the explicit overloads - (int) foo and - (int) fooint) intParam. This is due to Objective-C's named parameters being functionally equivalent to C++'s name mangling.
В Objc нет перегрузки функций по возращаемому типу данных.
На мой взгляд это преимущество. Которое не дает делать местами небезопасный код.

11)Objective-C will happily allow a method and a variable to share the same name, unlike C++ which will typically have fits. I imagine this is something to do with Objective-C using selectors instead of function pointers, and thus method names not actually having a "value".
ХЗ автор считает что указатели на функции лучше чем селекторы.
12)
Objective-C doesn't allow objects to be created on the stack - all objects must be allocated from the heap (either explicitly with an alloc message, or implicitly in an appropriate factory method).
Objective-C не позволяет создавать объекты в стеке - все объекты должны быть выделены из кучи (явно с сообщением Alloc или неявно в соответствующем заводским способом).

Вообщем. Тут используется ARC и именно этим обусловлено то что неявно нельзя не создать объект. Память должна быть выделена через alloc init (new).

13) Like C++, Objective-C has both structs and classes. However, where in C++ they are treated as almost exactly the same, in Objective-C they are treated wildly differently - you can create structs on the stack, for instance.
Objc поддерживает работу со структурами. struct Однако если внутрь структуры положить NSObject то могут возникнуть некоторые нюансы.

Добавлено через 7 минут
Он не понимает что такое "сборщик мусора". И не отличает ARC от него.
Слово "сборщик мусора" взято в кавычки чтобы лучше донести мысль. Так как словосочетание "счетчик ссылок" нужных ассоциаций вызывать не будет.
А принцип работы да, не спорю, разный.
1
0 / 0 / 0
Регистрация: 11.08.2014
Сообщений: 40
15.09.2014, 00:07  [ТС] 6
noname_club, спасибо вам огромное, вы очень помогли.
У меня есть одна проблема, когда я чего-то не знаю, я думаю, что у сделаю что-то не так или пойду по-непрвильному пути. Скажите пожалуйста, смогу ли я программровать под ios, Mac владея базовыми знаниями С++, а именно, "С++ базовый курс" от Герберта Шилдта?
Я хоть и не религиозный человек, но мне очень важно получить что-то вроде "благословения" что-ли)))
Заранее спасибо вам.
0
112 / 103 / 12
Регистрация: 01.05.2013
Сообщений: 603
15.09.2014, 05:32 7
в 8 пункте я бред видимо написал.

Вообщем незнаю точно о чем идет речь.

8) Objective-C allows assigning to self, and allows class initialisers (similar to constructors) to return a completely different class if desired. Contrast to C++, where if you create a new instance of a class (either implicitly on the stack, or explicitly through new) it is guaranteed to be of the type you originally specified.
8) Objective-C позволяет назначать на самоопределение, и позволяет класса инициализаторов (по аналогии с конструкторами), чтобы вернуться совершенно другой класс при желании. Отличие от C ++, где, если вы создаете новый экземпляр класса (либо неявно в стеке, или явно через новый) он гарантированно будет типа вы первоначально заданной.
Но точно знаю что в Objc можно переназначать имя класса уже существующего объекта.
И также можно пененазачить метод у любого объекта. на другой метод из его же.

Добавлено через 6 минут
пример кода с переназначением метода

http://stackoverflow.com/quest... 1#19902721

Objective-C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
@interface UIScreen (I_love_ios_7)
- (CGRect)bounds2;
- (CGRect)boundsForOrientation:(UIInterfaceOrientation)orientation;
@end
 
@implementation UIScreen (I_love_ios_7)
- (CGRect)bounds2
{
    return [self boundsForOrientation:[[UIApplication sharedApplication] statusBarOrientation]];
}
 
- (CGRect)boundsForOrientation:(UIInterfaceOrientation)orientation
{
    CGRect resultFrame = [self bounds2];
    if(UIInterfaceOrientationIsLandscape(orientation))
        resultFrame.size.width -= 20;
    else
        resultFrame.size.height -= 20;
    return resultFrame;
}
@end
 
void Swizzle(Class c, SEL orig, SEL new)
{
    Method origMethod = class_getInstanceMethod(c, orig);
    Method newMethod = class_getInstanceMethod(c, new);
    if(class_addMethod(c, orig, method_getImplementation(newMethod), method_getTypeEncoding(newMethod)))
        class_replaceMethod(c, new, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
    else
        method_exchangeImplementations(origMethod, newMethod);
}
 
@implementation AppDelegate
 
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
 
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
// << заменяем у класса UIScreen метод bounds на метод bounds2
        Swizzle([UIScreen class], @selector(bounds2), @selector(bounds)); 
// <<
        [application setStatusBarStyle:UIStatusBarStyleLightContent];
 
        self.window.clipsToBounds =YES;
 
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(applicationDidChangeStatusBarOrientation:)
                                                     name:UIApplicationWillChangeStatusBarOrientationNotification
                                                   object:nil];
        NSDictionary* userInfo = @{UIApplicationStatusBarOrientationUserInfoKey : @([[UIApplication sharedApplication] statusBarOrientation])};
        [[NSNotificationCenter defaultCenter] postNotificationName:UIApplicationWillChangeStatusBarOrientationNotification
                                                            object:nil
                                                          userInfo:userInfo];
    }
 
    return YES;
}
 
- (void)applicationDidChangeStatusBarOrientation:(NSNotification *)notification
{
    UIInterfaceOrientation orientation = [[notification.userInfo objectForKey: UIApplicationStatusBarOrientationUserInfoKey] intValue];
    CGSize size = [[UIScreen mainScreen] boundsForOrientation:orientation].size;
    int w = size.width;
    int h = size.height;
    float statusHeight = 20.0;
    switch(orientation){
        case UIInterfaceOrientationPortrait:
            self.window.frame =  CGRectMake(0,statusHeight,w,h);
            break;
        case UIInterfaceOrientationPortraitUpsideDown:
            self.window.frame =  CGRectMake(0,0,w,h);
            break;
        case UIInterfaceOrientationLandscapeLeft:
            self.window.frame =  CGRectMake(statusHeight,0,w,h);
            break;
        case UIInterfaceOrientationLandscapeRight:
            self.window.frame =  CGRectMake(0,0,w,h);
            break;
    }
}
@end
0
-6 / 3 / 0
Регистрация: 18.07.2012
Сообщений: 55
19.09.2014, 21:25 8
а теперь обратный вопрос
я на VS тока HelloWorld делал
программировать по сути начал с обчектива когда на кок#с сел
я если начну что-то на VS делать почувствую себя как в АДУ?
0
686 / 613 / 43
Регистрация: 13.01.2011
Сообщений: 1,722
19.09.2014, 21:34 9
Цитата Сообщение от EvilYarik Посмотреть сообщение
я если начну что-то на VS делать почувствую себя как в АДУ?
EvilYarik, попробуйте, потом расскажите, не?
0
-6 / 3 / 0
Регистрация: 18.07.2012
Сообщений: 55
20.09.2014, 00:33 10
zulkis, я слышал оттуда не возвращаются
0
20.09.2014, 00:33
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
20.09.2014, 00:33
Помогаю со студенческими работами здесь

Хочу начать программировать в objc. Опыта программирования нет. Что нужно?
Хоч начать программировать в objc. Опыта программирования нет. Что нужно? Сколь времени нужно чтобы...

Затруднение с пониманием. Как в ObjC добраться до свойств какого-нибудь контрола?
Приветствую всех ! не сочтите за труд и просветите начинающего.. Изучаю C# и Objective C...

Что проще начать изучать "с нуля" - Objc или 1C?
Добрый день, уважаемые форумчане! Начинаю изучать программирование, и меня в данный момент...

Отличия <%= %> от <%# %>
Знаю, что &lt;%# %&gt; срабатывает при биндинге. А когда срабатывает &lt;%= %&gt;? В чем разница?


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
10
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru