C++ Code in Objective-C Macintosh Applications

Objective-C provides object-oriented features for Macintosh application development, such as inheritance and polymorphism. The language is based on the C programming language; therefore, you can use your C programming knowledge to code within Objective-C. Objective-C++ is a bridge mechanism that allow Objective-C source modules to work with Objective-C++ classes, which could compile and link with C++ code libraries.


The following simple example of a square matrix shows the contents of a C++ header file for a Matrix class. The Matrix class comes with the standard constructor and destructor for a C++ class, and the methods are what you’d expect for a basic square matrix object:


class Matrix
{
public:
Matrix( int inSize );
virtual ~Matrix();
int getSize( void );
int getDeterminant( void );
void setElement( int inRow, int inCol, int inValue );
int getElement( int inRow, int inCol );
Matrix operator+( const Matrix& inAddend );
private:
int m_size;
int[][] m_elements;
};

To use Objective-C++, your Objective-C++ class modules must use the file extension .mm. This tells Xcode’s compiler that the class is to be compiled using Objective-C++, which will allow your class to use C++ language keywords. Using Objective-C++, your app could create a Matrix object to perform basic operations, such as adding two Matrix objects together. This assumes the Objective-C++ source module has #imported the C++ Matrix.h file:


- (void)addTwoMatrices
{
Matrix matrixOne( 3 ); // 3x3 matrix
Matrix matrixTwo( 3 ); // another
int rowIndex = 0;
int colIndex = 0;
for (rowIndex=0; rowIndex<3; ++rowIndex)
{
for (colIndex=0; colIndex<3; ++colIndex)
{
// set matrix one's elements to their values
matrixOne.setElement( rowIndex, colIndex, XXX );
// set matrix two's elements to some other values
matrixTwo.setElement( rowIndex, colIndex, YYY );
}
}
Matrix matrixSum = matrixOne + matrixTwo;

With Objective-C++, your apps are able to take advantage of all the available third-party libraries written for C++.




dummies

Source:http://www.dummies.com/how-to/content/c-code-in-objectivec-macintosh-applications.html

No comments:

Post a Comment