iOS C++学习之路

从iOS开发者的角度去学习c++ (本文Demo在Xcode编译器)

c++ 和 oc 都是c的超集 都有面向对象的语言特性 对于熟悉oc的开发者来说 从iOS开发者角度去尝试理解和着手开始学习C++

OC和 C++ 的差异比较

-在OC中你可以运用技术手段拿到所在类的所有方式函数和属性 无论.h文件中是否暴露你都可以利用method swizzling去修改或获得 本质是因为OC实在运行时确定

-而在C++中 由于在编译时确定 所以对作用域外的函数或成员变量成员函数进行操作

文件差异

OC 和 C++ 都包含 h(hpp)和m(cpp)

-OC中

//GLOCPerson.h 文件
#import 

@interface GLOCPerson : NSObject

@end

//GLOCPerson.m
#import "GLOCPerson.h"

@implementation GLOCPerson

@end

-C++中

//GLPerson.hpp
#ifndef GLPerson_hpp
#define GLPerson_hpp

#include 

#endif /* GLPerson_hpp */


//GLPerson.cpp
#include "GLPerson.hpp"


在C++中的实现文件中什么都没有,不需要像OC那样@implementation和@end来开始和结束
在OC中我们导入头文件通常#import xxx 这样编译器可以放置头文件重复导入 而在C++中使用#include 头文件是否重复导入需要开发者自己检查

成员变量和成员函数

对于成员变量我们可以在实现文件中定义(.m) 这样对于外界而言相当于私有成员变量(通过runtime手段获得就另说了)相当于C++的private
如果在.h文件中定义的话相当于任何其他的类都能访问 相当于C++的public

-OC中

#import "GLOCPerson.h"

@interface GLOCPerson ()
@property (nonatomic,strong)NSString*name;
@property (nonatomic,assign)NSInteger age;
@end
@implementation GLOCPerson

-(NSInteger)myAge:(NSInteger)age{
    return 0;
}

@end

-C++中

#ifndef GLPerson_hpp
#define GLPerson_hpp

#include 
#include 
class GLPerson {
private:
    std::string name;
    int age;
    
public:
    std::string name1;
    int age1;
    
    int myAge(int age);
    
};
#endif /* GLPerson_hpp */
需要注意的std::string name;是在OC中没有重命名空间这个概念 在不同的类中是允许相同的函数的
但在C++中为了解决命名冲突的事件会利用双冒号来表示 看下面的
namespace MyNamespace {

    class GLPerson { … };

}

namespace LibraryNamespace {

    class GLPerson { … };

}


//MyNamespace:: GLPerson pOne;

//LibraryNamespace:: GLPerson pTwo;


这样加上前缀区分了不同的类

在oc调用函数以及方法

#import "ViewController.h"
#include "GLPerson.hpp"
#include 
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    GLPerson cPlusPerson;
    cPlusPerson.name1 = "123";
    cPlusPerson.age1 = 12;
//    NSLog(@"%@   %d",cPlusPerson.name1,cPlusPerson.age1);
    std::cout<< "Lefe_x age is " << cPlusPerson.name1 << cPlusPerson.age1 << std::endl;
    
    // Do any additional setup after loading the view.
}

需要注意的是oc和c++混编需要将.m修改为.mm

运行工程看下打印信息


截屏2021-02-10 上午11.25.02.png

你可能感兴趣的:(iOS C++学习之路)