oc中如何呼叫c++的方法
阿新 • • 發佈:2019-02-06
ios討論群1群:135718460
有的時候,我們需要呼叫純c++的方法,這個時候,我們必須再次封裝一下。通過呼叫中間層物件的方法,來呼叫c++的方法。請看下圖:
2.在test.h檔案中定義方法
#ifndef __test__
#define __test__
class Test
{
public:
void test();
static void testStatic();
};
#endif
2.1.在test.cpp中實現定義的方法
#include "test.h" #include <iostream> void Test::test() { printf("Hellow world \n"); } void Test::testStatic() { printf("Hellow world with Static"); }
3.在RootViewController.h檔案中定義oc需要呼叫的方法
-(void)testFunc;
3.1在RootViewController.mm檔案中實現上方法,並且和c++檔案建立聯絡
#import "RootViewController.h" #include "test.h" static Test* pTest=NULL; @implementation testObject -(id)init { if (self=[super init]) { if (!pTest) { pTest=new Test(); } } return self; } -(void)testFunc { if (pTest) { pTest->test(); //-> c++ 指標 呼叫 公有變數和方法 //. c++ 物件 呼叫 公有變數和方法 } Test::testStatic(); } - (void)dealloc { if (pTest) { delete pTest; } [super dealloc]; } @end
4.在viewControler的viewdidLoad方法中例項化一個RootViewController物件並且呼叫在RootViewController.h宣告的方法
testObject * ttt=[[testObject alloc] init];
[ttt testFunc];
5.執行檢視列印結果