Loading [MathJax]/extensions/tex2jax.js

2015年8月16日日曜日

いろんな言語でOOPする

そろそろObjective-Cの勉強もしたくなったのいろんな言語でOOPしてみました。 Javaで書いた1+2だけをするプログラムををC++/Objective-C/Swiftで書いてみます。 これで少しiPhoneアプリのソースも読めそうです。 あとObjective-Cの硬い感じに慣れるとSwiftのチャラっとした感じは受け付けないのも少し理解できました。 ただ結局iPhoneもAndroidもロジックは同じC++が使えるのでC++が結局生き残るだろうなとも思います。 リソース管理はスマートポインタで少し改善できているし、最終的にC++でないとできないことも多いだろうし。

Java

interface Calculator{
int add();
}
view raw Calculator.java hosted with ❤ by GitHub
class CalculatorImpl implements Calculator{
private int a,b;
CalculatorImpl(int a, int b){
this.a = a;
this.b = b;
}
public int add(){
int c = a + b;
return c;
}
}
class Main{
public static void main(String args[]){
Calculator calc = new CalculatorImpl(1,2);
int result = calc.add();
System.out.println(result);
}
}
view raw Main.java hosted with ❤ by GitHub

C++

#include "calculator.h"
calculator::calculator(int a, int b){
this->a = a;
this->b = b;
}
int calculator::add(){
int c = a + b;
return c;
}
view raw calculator.cpp hosted with ❤ by GitHub
#ifndef Calc_calc_h
#define Calc_calc_h
class calculator{
private:
int a,b;
public:
calculator(int a, int b);
int add();
};
#endif
view raw calculator.h hosted with ❤ by GitHub
#include <iostream>
#include <memory>
#include "calculator.h"
using namespace std;
int main(int argc, const char * argv[]) {
//calculator *calc = new calculator(1,2);
unique_ptr<calculator> calc(new calculator(1,2));
int result = calc->add();
cout << result << endl;
//delete calc;
return 0;
}
view raw main.cpp hosted with ❤ by GitHub

Objective-C

#ifndef Calc_objc_Calculator_h
#define Calc_objc_Calculator_h
#import <Foundation/Foundation.h>
@interface Calculator : NSObject{
@private
int a,b;
}
-(id)initWithNum:(int)a b: (int)b;
-(int)add;
@end
#endif
view raw calculator.h hosted with ❤ by GitHub
#import <Foundation/Foundation.h>
#import "Calculator.h"
@implementation Calculator
-(id)initWithNum:(int)a b:(int)b{
if(self = [super init]){
self->a = a;
self->b = b;
}
return self;
}
-(int)add{
int c = a + b;
return c;
}
@end
view raw calculator.m hosted with ❤ by GitHub
#import "Calculator.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Calculator * calc = [[Calculator alloc]initWithNum: 1 b:2];
int result = [calc add];
NSLog(@"%d",result);
}
return 0;
}
view raw main.m hosted with ❤ by GitHub

Swift

class Calculator:CalculatorProtocol{
var a: Int
var b: Int
init(a: Int, b: Int){
self.a = a
self.b = b
}
func add() -> Int{
let c = a + b
return c
}
}
import Foundation
protocol CalculatorProtocol{
func add() -> Int
}
var calc = Calculator(a:1,b:2)
var result = calc.add()
println(result)
view raw main.swift hosted with ❤ by GitHub