rubyに関する記事一覧→ rubyのまとめ
node.jsに関する記事一覧→ node.jsのまとめ
クラス定義っていろんな言語使ってるとなんかごっちゃになってしまいますよね
そこで、各言語の超基本的なクラス定義を書き並べて比較してみることにしました
全てやっていることは同じで、Nekoクラスを定義して 名前を「ミケ」にセットして、挨拶をさせています
c++
#include <iostream> #include <stdio.h> //printf用 class Neko { private: std::string name; public: Neko(std::string new_name) { name = new_name; }; void hello() { std::cout << "吾輩は " << name << " である" << std::endl; // c++的にはこちらの方が一般的? printf("吾輩は %s である", name.c_str()); // prinfで出力する場合は c_strでchar*に変換する }; }; int main(int argc, char* argv[]) { Neko mike = Neko("ミケ"); mike.hello(); };
node.js
#!/usr/local/bin/node class Neko{ constructor(new_name){ this.name = new_name; }; hello(){ console.log('吾輩は '+ this.name + ' である'); }; }; const mike = new Neko('ミケ'); mike.hello();
ruby
#!/usr/local/bin/ruby -Ku class Neko def initialize(new_name) @name = new_name end def hello() puts('吾輩は ' << @name << ' である') end end mike = Neko.new('ミケ') mike.hello()
python3
#!/usr/bin/python3 class Neko: def __init__(self, new_name): self.name = new_name def hello(self): print("吾輩は " + self.name + " である") mike = Neko("ミケ") mike.hello()
C#
namespace NekoApp { class Neko { private string name; public Neko(string new_name) { name = new_name; } public void hello() { System.Console.WriteLine("吾輩は " + name + " である"); } } class NekoMain { static void Main() { Neko mike = new Neko("ミケ"); mike.hello(); } } }
java
class Neko{ private String name; public Neko(String new_name){ name = new_name; }; public void hello(){ System.out.println("吾輩は " + name + " である"); }; }; public class ClassTest{ public static void main(String[] args){ Neko mike = new Neko("ミケ"); mike.hello(); }; };