C ++ and objective-C

Source: Internet
Author: User

C ++ and objective-C

Using C ++ with objective-C
Apple's objective-C compiler allows users to freely mix C ++ and objective-C in the same source file. The compiled language is objective-C ++. With it, you can use the existing C ++ class library in the objective-C application.

Key Points of objective-C and C ++ hybrid editing
In objective-C ++, you can call methods using C ++ code or from objective-C. In both languages, objects are pointers and can be used anywhere. For example, the C ++ class can use the objective-C object pointer as a data member, and the objective-C class can also have the C ++ object pointer as an instance variable. This is illustrated in the following example.
Note: xcode requires the source file ". MM" as the extension to start the objective-C ++ extension of the compiler.
/* Hello. Mm
* Compile with: G ++-x objective-C ++-framework Foundation hello. Mm-O hello
*/

# Import <Foundation/Foundation. h>
Class Hello {
PRIVATE:
Id greeting_text; // holds an nsstring
Public:
Hello (){
Greeting_text = @ "Hello, world! ";
}
Hello (const char * initial_greeting_text ){
Greeting_text = [[nsstring alloc] initwithuf8string: initial_greeting_text];
}
Void say_hello (){
Printf ("% s/n", [greeting_text utf8string]);
}
};

@ Interface greeting: nsobject {
@ Private
Hello * Hello;
}
-(ID) Init;
-(Void) dealloc;
-(Void) saygreeting;
-(Void) saygreeting :( hello *) greeting;
@ End

@ Implementation greeting
-(ID) Init {
If (Self = [Super init]) {
Hello = new Hello ();
}
Return self;
}
-(Void) dealloc {
Delete hello;
[Super dealloc];
}
-(Void) saygreeting {
Hello-> say_hello ();
}
-(Void) saygreeting :( hello *) greeting {
Greeting-> say_hello ();
}
@ End

Int main (){
NSAID utoreleasepool * Pool = [[NSAID utoreleasepool alloc] init];

Greeting * greeting = [[greeting alloc] init];
[Greeting saygreeting]; //> Hello, world!

Hello * Hello = new Hello ("Bonjour, monde! ");
[Greeting saygreeting: Hello]; //> bonjour, monde!

Delete hello;
[Greeting release];
[Pool release];
Return 0;
}

Just as you can declare the C structure in the OC interface, you can also declare the C ++ class in the OC interface. Similar to the C structure, the C ++ class defined in the OC interface has a global scope, not an embedded class of the OC class (this is similar to the Standard C (although not c ++) the definition of the improved nested structure is consistent with the file range ).
To allow you to write code based on language variants, the OC ++ compiler defines _ cplusplus and _ objc _ Preprocessor constants, respectively specifying C ++ and OC. As mentioned above, the OC ++ class does not allow the C ++ class to inherit from the OC object or the OC class to inherit from the C ++ object.
Class base {/*...*/};
@ Interface objcclass: Base... @ end // error!
Class derived: Public objcclass... // error!

Different from OC, C ++ objects are of the static type, and running polymorphism is a special case. The object models of the two languages are therefore not directly compatible. More fundamentally, the layout of OC and C ++ objects in the memory is incompatible. That is to say, it is generally impossible to create an object instance. Therefore, the two types of hierarchies cannot be mixed.
You can declare C ++ classes in the OC class, And the compiler treats these classes as declared in the global namespace. Like the following:

@ Interface Foo {
Class bar {...} // OK
}
@ End

Bar * barptr; // OK

The OC allows the C structure as an instance variable, whether or not it is declared inside the OC declaration.

@ Interface Foo {
Struct cstruct {...};
Struct cstruct bigivar; // OK
}... @ End

After Mac OS X 10.4, if you set the fobjc-call-cxx-cdtors compiler flag, you can use a C ++ class instance that contains virtual functions and meaningful user-defined zero-parameter constructor, destructor as an instance variable (the gcc-4.2 sets the compiler flag by default fobjc-call -CPP-cdtors ). After the OC member variable alloc is complete, the alloc function calls the constructor in the declared order. The constructor uses a common constructor without parameters. Before the OC member variable dealloc, The dealloc method calls the destructor in reverse order of declaration. OC has no namespace concept. The OC class cannot be declared in the C ++ namespace or in the OC class.
The OC class, protocol, and classification cannot be declared in the C ++ template, and the C ++ template cannot be declared in the OC interface, protocol, or classification scope.
However, the OC class can be used as the C ++ template parameter, and the C ++ template parameter can also be used as the receiver or parameter of the OC message expression (not through selector ).

C ++ vocabulary ambiguity and conflict
The OC header file defines some identifiers, which must be included by all OC programs. These identifiers recognize IDs, classes, Sel, IMP, and bool.
In the OC method, the compiler predeclares the identifiers self and super, and considers the keyword this in C ++. Unlike this in C ++, self and super are context-related. They can also be used for common identifiers in addition to OC methods.
The parameter list of methods in the protocol has five contextual keywords (oneway, in, out, inout, bycopy ). These are not keywords in other content.
From the perspective of OC programmers, C ++ has added many new keywords. You can still use the C ++ keyword as part of the OC selector, so the impact is not serious, but you cannot use them to name the OC class and instance variables. For example, although the class is the key word of C ++, you can still use the nsobject method class:
[Foo class]; // OK

However, because it is a keyword, you cannot use class as the variable name:

Nsobject * class; // Error

The class name and category name in OC have separate namespaces. @ Interface Foo and @ interface (FOO) can coexist in the source code. In OC ++, you can also use the class name or structure name in C ++ to name your category.
The protocol and template identifier use the same syntax but have different purposes:

ID <someprotocolname> Foo;
Templatetype <sometypename> bar;

To avoid such ambiguity, the compiler does not allow the ID to be the Template Name. Finally, C ++ has a syntax ambiguity. When a label is followed by an expression to indicate a global name, it is like the following:
Label: global_name = 3;

A space is required after the first colon. In similar cases, OC ++ also requires a space:

Extends er selector: global_c ++ _ name;

 

Restrictions
OC ++ does not provide C ++ or C ++ functions for OC classes. For example, you cannot use the OC syntax to call C ++ objects, add constructor and destructor to OC objects, or replace this and self. The architecture of the class is independent. C ++ classes cannot inherit OC classes, and OC classes cannot inherit C ++ classes. In addition, multi-language exception handling is not supported. That is to say, the exception thrown by an OC cannot be captured by the C ++ code. In turn, the exception thrown by the C ++ Code cannot be captured by the OC code.

Http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocCPlusPlus.html

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.