クラスの定義をいろんな言語で書いてみた

まとめリンク: 同じことをいろんな言語で書いてみたシリーズ



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();
};


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()


Crystal

class Neko
  @name: String
  def initialize(new_name)
    @name = new_name
  end
  def hello()
    puts("吾輩は #{@name} である")
  end
end
mike = Neko.new("ミケ")
mike.hello()


Rust

struct Neko {
  name: String,
}
impl Neko {
  fn hello(&self) {
    println!("吾輩は {} である", self.name);
  }
}
fn main() {
  let mike = Neko{name: "ミケ".to_string()};
  mike.hello();
}


Python3

#!/usr/bin/python3
class Neko:
  def __init__(self, new_name):
    self.name = new_name
  def hello(self):
    print(f"吾輩は {self.name} である")
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();


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();
    }
  }
}