主流编程语言语法简单总结(Java, C, C++, C#, PHP, JavaScript, Swift, Go)

发布时间 2023-08-02 15:59:15作者: cps666

原文地址 blog.csdn.net

经常用到多种编程语言,时间长了容易搞混,整理一下不用语言语法的异同点,方便快速学习或温习。

根据 TIOBE 编程语言排行榜,语言顺序是 Java, C, C++, Python, Visual Basic .NET, C#, PHP, JavaScript(简称 JS), SQL, Swift,MATLAB, Go,其中 Python 和 Visual Basic .NET 语法比较特别,SQL 主要是访问和处理数据库,MATLAB 主要是数学方面,所以只整理八种语言。

TIOBE 发布的 2018 年 10 月编程语言排行榜:

Oct 2018Oct 2017Programming LanguageRatingsChange主要使用场景
11Java17.801%+5.37%web 后端,游戏后端,大数据,Android
22C15.376%+7.00%各种核心库,嵌入式
33C++7.593%+2.59%各种后端(除 web)
45Python7.156%+3.35%机器学习,大数据
58Visual Basic .NET5.884%+3.15%Win 平台下的 APP、web 后端
64C#3.485%-0.37%Win 平台下的 APP、web 后端,Unity3D
77PHP2.794%+0.00%web 后端
86JavaScript2.280%-0.73%web 前端,Node.js
9-SQL2.038%+2.04%数据库
1016Swift1.500%-0.17%iOS
1113MATLAB1.317%-0.56%数学计算
1220Go1.253%-0.10%高性能分布式后端

主要参考:菜鸟教程(Java 教程C 语言教程C++ 教程Python 3 教程C# 教程PHP 教程JavaScript 教程Node.js 教程SQL 教程Swift 教程Go 语言教程

文章目录

基础语法

Hello World

//java
public class HelloWorld {
    public static void main(String []args) {
        System.out.println("Hello, World!");
    }
}

//c
#include <stdio.h>
int main(){
   printf("Hello, World! \n");
   return 0;
}

//cpp
#include <iostream>
using namespace std;
int main(){
   cout << "Hello, World!";
   return 0;
}

//csharp
using System;
namespace HelloWorldApplication{
   class HelloWorld{
      static void Main(string[] args){
         Console.WriteLine("Hello, World!");
         Console.ReadKey();
      }
   }
}

<!DOCTYPE html> 
<html> 
<body> 
<?php
	echo "Hello, World!"; 
?> 
</body> 
</html>

//Node.js
console.log("Hello, World!");

//javascript
<!DOCTYPE html>
<html>
<body>
<script>
	document.write("<p>Hello, World!</p>");
</script>
</body>
</html>

//swift
import UIKit
var myString = "Hello, World!"//Swift语言没有";"
print(myString)

//go
func main(){  
//{  //{不能在单独的行上,其他语言没这个问题
    fmt.Println("Hello, World!")//Go语言没有";"
}

标识符

类名、变量名以及方法名都被称为标识符。

  • 所有的标识符都以字母(A-Z 或者 a-z)或下划线(_)开始(Java、JS 可用 $,C# 可用 @开始)
  • 首字符之后可以是字母(A-Z 或者 a-z)、下划线(_)或数字(0-9)的任何字符组合(Java、JS 可用 $,C# 可用 @)
  • 关键字不能用作标识符
  • 标识符是大小写敏感的
  • 合法标识符举例:age、_value、__1_value
  • 非法标识符举例:123abc、-salary

空格

空格分隔语句的各个部分。

int age;//age前至少一个空格
fruit = apples + oranges; //fruit 和 =,或者 = 和 apples 之间的空格字符不是必需的,只是为了增强可读性

let a= 1 + 2 //在Swift中,运算符不能直接跟在变量或常量的后面,这样会报错

注释

//这是单行注释
/*这也是单行注释*/
/* 这是多行注释
 * 这是多行注释
 */

数据类型

  • java: byte, short, int, long, float, double, boolean, char, 引用类型(类似 C 的指针,对象、数组)
  • C: char, unsigned char, signed char, int, unsigned int, short, unsigned short, long, unsigned long, float, double, long double, void
  • C++: bool, char, int, float, double, void, wchar_t, (可加 signed, unsigned, short, long 修饰), (typedef int feet; feet varA;// 定义新类型),
  • C#: bool, byte, char, decimal, double, float, int, long, sbyte, short, uint, ulong, ushort
  • PHP: String, Integer, Float, Boolean, Array, Object, NULL
  • JS: String, Number, Boolean, Null, Undefined, Symbol, 引用类型(Object, Array, Function)
  • Swift: Int, UInt, Int8, UInt8, Int32, UInt32, Int64,UInt64, Float, Double, Bool, String, Character, Optional
  • Go: bool, int, uint8(byte), uint16, uint, unit32, uint64, int8, int16, int32(rune), int64, float32,float64, complex64, complex128, uintptr(无符号整型,用于存放一个指针), 派生类型(指针 Pointer,数组,结构化 struct,Channel,函数,切片,接口类型 interface,Map )

变量类型

  • Java, C, C++, C#: int varA;, int varA = 42;
  • PHP: $varA=42;
  • JS: var varA;, var varA = 42;, let varA = 42;(let 是 ES6 引入,声明的变量只在代码块有效,不影响同名块外变量)
  • Swift: var varA:Int, var varA = 42
  • Go: var varA int, var varA = 42, varA := 42

Swift 可选 (Optionals) 类型

Swift 的可选(Optional)类型,用于处理值缺失的情况。可选表示 "那儿有一个值,并且它等于 x “或者" 那儿没有值”。
Swfit 语言定义后缀?作为命名类型 Optional 的简写,换句话说,以下两种声明是相等的:

var optionalInteger: Int?
var optionalInteger: Optional<Int>

当你确定可选类型确实包含值之后,你可以在可选的名字后面加一个感叹号(!)来获取值。这个感叹号表示 "我知道这个可选有值,请使用它。" 这被称为可选值的强制解析(forced unwrapping)。

var myString:String?
myString = "Hello, Swift!"
print(myString)//正常输出
print( myString! )// 强制解析

程序执行结果为:

Optional("Hello, Swift!")
Hello, Swift!

常量

  • Java:使用 final 关键字来修饰常量,final int CONSTA = 42;
  • C, C++: #define CONSTA 42, const int CONSTA = 42;
  • C#: const int constA = 42;
  • PHP: define("CONSTA", 42);
  • JS: const constA=42;(ES6 引入)
  • Swift: let constA = 42
  • Go: const CONSTA int = 42, const CONSTA = 42

运算符

  • 算术运算符: +, -, *, /, %, ++(Swift3 取消), --(Swift3 取消)
  • 关系运算符: ==, !=, >, <, >=, <=, ===(绝对等于,PHP、JS 特有), !==(绝对不等于,PHP、JS 特有), <>(不等于,PHP 特有)
  • 逻辑运算符: &&与, ||或, !非,(PHP 特有:and, or, xor)
  • 位运算符: &与, |或, ^异或,~反, <<左移, >>右移,>>>右移补 0(Java 特有) ,(PHP、JS 没有位运算符)
  • 赋值运算符: =, +=, -=, *=, /=, %=, <<=, >>=, &=, ^=, |=, (PHP、JS 没有移位和逻辑赋值)
  • 其他运算符:
    • ? :(条件运算符,JS、Go 没有)
    • instanceof(检查对象类型,Java 特有)
    • &(返回变量地址,C、C++、C#、Go 特有)
    • *(指针变量,C、C++、C#、Go 特有)
    • sizeof()(返回字节数,C、C++、C# 特有)
    • ,(顺序执行一系列运算,只返回最后表达式的值,C++ 特有)
    • Cast(强制转换,C++ 特有))
    • .=(连接字符串,PHP 特有)
    • typeof()(返回 class 类型,C# 特有)
    • is(检查对象类型,C# 特有),
    • as(强制转换,C# 特有)

判断

if(布尔表达式){//Swift、Go表达式外面没括号
	//如果布尔表达式为true将执行的语句
}

if(布尔表达式){
   	//如果布尔表达式的值为true
}else{
   	//如果布尔表达式的值为false
}

if(布尔表达式 1){
   	//如果布尔表达式 1的值为true执行代码
}else if(布尔表达式 2){ //PHP也可以写成elseif
   	//如果布尔表达式 2的值为true执行代码
}else if(布尔表达式 3){
   	//如果布尔表达式 3的值为true执行代码
}else {
   	//如果以上布尔表达式都不为true执行代码
}

if(布尔表达式 1){
	//如果布尔表达式 1的值为true执行代码
   	if(布尔表达式 2){
      	//如果布尔表达式 2的值为true执行代码
  	}
}

switch(expression){
	case value :
       	//语句
       	break; //可选
    case value :
       	//语句
       	break; //可选
    //你可以有任意数量的case语句
    default : //可选
       //语句
}

循环

//好像Go没有
while( 布尔表达式 ) {
  	//循环内容
}

//Swift不用do,用repeat
//好像Go没有
do {
	//代码语句
}while(布尔表达式);

//Swift3已弃用
//for(初始化; 布尔表达式; 更新)
for(int x = 10; x < 20; x = x+1) {
    //代码语句
}

//for/in Java5以上
//for(声明语句 : 表达式)
for(int x : numbers ){
   //代码句子
}
for(Iterator i = list.iterator(); i.hasNext(); ) {
   Object listElement = i.next();
}

//forEach,Java8以上
List<Integer> numbers = new ArrayList<>();
numbers.forEach((Integer integer) -> {//第一种
    System.out.println(integer);
});
numbers.forEach(integer -> {//第二种
    System.out.println(integer);
});
numbers.forEach(integer -> System.out.println(integer));//第三种
numbers.forEach(System.out::println);//第四种

numbers.forEach(new MyConsumer());第五种,基于MyConsumer类
class MyConsumer implements Consumer<Integer>{
    @Override
    public void accept(Integer integer) {
        System.out.println(integer);
    }
}

//stream,Java8以上
arrayList.stream().filter(i -> i > 0);
arrayList.stream().forEach(s -> System.out.println(s));

//C#
foreach (int element in fibarray){
	System.Console.WriteLine("Element #{0}", element);
}

//PHP
foreach ($array as $value){
   //要执行代码;
}

//JS
for (x in person){  // x 为属性名
    txt=txt + person[x];
}

//Swift
for index in 1...5 {
    print("\(index) 乘于 5 为:\(index * 5)")
}
var someInts:[Int] = [10, 20, 30]
for index in someInts {
   print( "index 的值为 \(index)")
}

字符串

//java
String hello = "Hello, world!";
char[] helloArray = {'H', 'e', 'l', 'l', 'o'};
hello = new String(helloArray);
hello.concat(", ");
hello + "world!";

//C, C++
char hello[12] = {'H', 'e', 'l', 'l', 'o', '\0'};
char world[] = " world";
strcat(hello, world);

//C++, C#
string hello = "Hello";
string world = " world";
string str
str = hello + world;

//php
$hello="Hello";
$world="World";
echo $hello . " " . $world;

//JS
var hello = "Hello";
var hello1 new String("Hello");
(hello === hello1) //结果为 false,因为hello是字符串,hello1是对象

//Swift
var hello = "Hello";
var hello1 = String("Hello");

//Go
var hello string
hello = "Hello"
world := "world"

数组

//Java, C, C++, C#
dataType[] arrayRefVar = new dataType[arraySize];//C, C++不需要new
double[] myList = {1.9, 2.9, 3.4, 3.5};

//PHP
$cars=array("Volvo","BMW","Toyota");

//JS
var myCars=new Array("Saab","Volvo","BMW");
var myCars=["Saab","Volvo","BMW"];

//Swift
var someArray = [SomeType](repeating: InitialValue, count: NumbeOfElements)
var someInts = [Int](repeating: 0, count: 3)//类型为Int数量为 3,初始值为0的数组:
var someInts:[Int] = [10, 20, 30]

//Go
var variable_name [SIZE] variable_type
var balance = [4]float32{2.0, 3.4, 7.0, 50.0}
var balance = [...]float32{2.0, 3.4, 7.0, 50.0}//Go语言会根据元素的个数来设置数组的大小

结构体

//Java要用第三方库Javastruct,用于像处理 C 或者 C++ 结构体那样处理 java 对象
	@StructClass 
	public class Foo {
		@StructField(order = 0)
		public byte b;
		@StructField(order = 1)
		public int i;
	}

//C, C++
struct {//这个结构体并没有标明其标签
    int a;
    char b;
    double c;
} s1;//同时又声明了结构体变量s1
 
struct SIMPLE{ //结构体的标签被命名为SIMPLE
    int a;
    char b;
    double c;
};//没有声明变量
struct SIMPLE t1, t2[20], *t3;//用SIMPLE标签的结构体,声明变量t1、t2、t3

typedef struct { //也可以用typedef创建新类型
    int a;
    char b;
    double c; 
} Simple2;
Simple2 u1, u2[20], *u3;//现在可以用Simple2作为类型声明新的结构体变量

//C位域
struct{
  unsigned int width : 16;//带有预定义宽度的变量被称为位域
  unsigned int height : 16;
} Rect;//总共占用32位,即4个字节

//C共用体是一种特殊的数据类型,允许你在相同的内存位置存储不同的数据类型
union Data{
   int i;
   char  str[20];
} data;
union Data data;        
data.i = 10;
strcpy( data.str, "C Programming");//data.i会改成1917853763


//C#
struct Books{ //类是引用类型,结构是值类型
   private string title;
   private int book_id;
   public void getValues(string t, int id){//可带有方法
      title = t;
      book_id =id; 
   }

//Swift
struct MarksStruct {
   var mark: Int
   init(mark: Int) {
      self.mark = mark
   }
}
var aStruct = MarksStruct(mark: 98)
var bStruct = aStruct //aStruct和bStruct是使用相同值的结构体!

//Go
type Books struct {
   title string
   book_id int
}
var Book1 Books/* 声明 Book1 为 Books 类型 */
Book1.title = "Go 语言"

指针

指针是一个变量,其值为另一个变量的地址,即,内存位置的直接地址。

//C, C++
int  a = 20;	/* 实际变量的声明 */
int  *ip;     	/* 指针变量的声明 */
ip = &a;  	/* 在指针变量中存储 a 的地址 */
int *ptr = NULL;//NULL 指针是一个定义在标准库中的值为零的常量, ptr的地址是 0x0
printf("Address of a variable: %p\n", &a  );
printf("Address stored in ip variable: %p\n", ip );/* 在指针变量中存储的地址 */  
printf("Value of *ip variable: %d\n", *ip ); /* 使用指针访问值 */

//Go
var a int= 20   /* 声明实际变量 */
var ip *int        /* 声明指针变量 */
ip = &a  /* 指针变量的存储地址 */
var  ptr *int//空指针,当一个指针被定义后没有分配到任何变量时,它的值为 nil
fmt.Printf("a 变量的地址是: %x\n", &a  )
fmt.Printf("ip 变量储存的指针地址: %x\n", ip )/* 指针变量的存储地址 */
fmt.Printf("*ip 变量的值: %d\n", *ip )/* 使用指针访问值 */


函数(方法)

//Java, C, C++, C#
修饰符 返回值类型 方法名(参数类型 参数名){
    方法体
    return 返回值;
}

//PHP, JS
function functionName(){
    // 要执行的代码
}

//Swift
func funcname(Parameters) -> returntype {
    //要执行的代码
    return parameters
}

//Go
func function_name( [parameter list] ) [return_types] {
   函数体
}

异常处理

//Java
public void deposit(double amount) throws RemoteException{
//如果一个方法没有捕获到一个检查性异常,那么在方法签名的尾部使用throws关键字来声明。
   	// Method implementation
   	int a[] = new int[2];
    try{//使用 try 和 catch 关键字可以捕获异常
       System.out.println("Access element three :" + a[3]);
    }catch(ArrayIndexOutOfBoundsException e){
       System.out.println("Exception thrown  :" + e);
    }finally{//无论是否发生异常,finally 代码块中的代码总会被执行。
       a[0] = 6;
       System.out.println("First element value: " +a[0]);
    }
    throw new RemoteException();//也可以使用 throw抛出一个异常,无论它是新实例化的还是刚捕获到的。
}

//C
   pf = fopen ("unexist.txt", "rb");
   if (pf == NULL){
      errnum = errno;
      fprintf(stderr, "错误号: %d\n", errno);//错误号: 2
      perror("通过 perror 输出错误");//通过 perror 输出错误: No such file or directory
      fprintf(stderr, "打开文件错误: %s\n", strerror( errnum ));//打开文件错误: No such file or directory
   }

//C++
struct MyException : public exception{
  	const char * what () const throw ()  {
    	return "C++ Exception";
  }
};
try{
  	throw MyException();
}catch(MyException& e){
  	std::cout << e.what() << std::endl;//C++ Exception
}

//C#
try{
    result = num1 / num2;
}catch (DivideByZeroException e){
    Console.WriteLine("Exception caught: {0}", e);
}finally{
    Console.WriteLine("Result: {0}", result);
}

//PHP
try {
    echo inverse(5) . "\n";
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
} finally {
    echo "First finally.\n";
}

//JS
try { 
  	if(x == "")  throw "值为空";
} catch(err) {
    message.innerHTML = "错误: " + err;
} finally {
  	document.getElementById("demo").value = "";
}

//Swift
let tmpX = try? canThrowErrors(type: 1)  //如果抛出异常程序正常运行并赋值nil给左侧, 如果没抛异常则将返回值赋给左侧
let tmpY = try! canThrowErrors(type: 2)  //你很确定不会抛出异常时这样用,但如果运行时抛异常会导致程序崩溃

func canThrowErrors() throws -> String //throws后面不用跟着异常类

do {
    var data = try canThrowErrors(type: 3)//函数可能抛出异常
    print("after execute canThrowErrors")
    if data != nil {
        print("Error test data:\(data)")
    }
} catch VendingMathineError.outOfStack {
    print("outOfStack")
} 

defer {//类似finally,抛出异常就执行defer,未抛出异常就最后执行defer
	print("testDefer exit")
}

//Go
//错误处理
type error interface {
    Error() string
}
func Sqrt(f float64) (float64, error) {
    if f < 0 {
        return 0, errors.New("math: square root of negative number")
    }
    // 实现
}

//Go语言追求简洁优雅,所以,Go语言不支持传统的 try…catch…finally 这种异常,因为Go语言的设计者们认为,将异常与控制结构混在一起会很容易使得代码变得混乱。因为开发者很容易滥用异常,甚至一个小小的错误都抛出一个异常。在Go语言中,使用多值返回来返回错误。不要用异常代替错误,更不要用来控制流程。在极个别的情况下,也就是说,遇到真正的异常的情况下(比如除数为0了)。才使用Go中引入的Exception处理:defer(类似finally), panic(类似throw), recover(恢复错误)。
func main() {
	funcA()
	funcB()
	funcC()
}
//Go没有异常机制,但有panic/recover模式来处理错误
func funcA() {
	fmt.Println("没有发生异常,funcA正常执行。")
}
func funcB() {
	defer func() {//必须先声明defer,否则不能捕获到panic异常
		if err := recover(); err != nil {//recover只有在defer调用的函数中有效
			fmt.Println("捕获到panic产生的异常:", err) // 这里的err其实就是panic传入的内容
			fmt.Println("recover恢复过来")
		}
	}() //()就是调用该匿名函数的,必须写 
	//panic一般会导致程序挂掉(除非recover),然后Go运行时会打印出调用栈
	//但是,关键的一点是,即使函数执行的时候panic了,函数不往下走了,运行时并不是立刻向上传递panic,而是到defer那,等defer的东西都跑完了,panic再向上传递。所以这时候defer有点类似 try-catch-finally 中的 finally。panic就是这么简单。抛出个真正意义上的异常。
	panic("funcB要抛出一个异常了,等下defer会通过recover捕获这个异常,捕获到时,在funcB不会输出,会在defer里被捕获输出,然后正常处理,使后续程序正常运行。注意,在funcB函数里,排在panic后面的代码不会执行。")
	fmt.Println("funcB里panic后面要打印出的内容。但是永远也打印不出来。因为逻辑并不会恢复到panic那个点去,函数还是会在defer之后返回,也就是说执行到defer后,程序直接返回到main()里,接下来开始执行funcC()")
} 
func funcC() {
	fmt.Println("没有defer来recover捕获panic的异常,funcC不会被正常执行.")
}

//Java
package net.java.util;//Java 提供了包机制,用于区别类名的命名空间。
public class Something{
   ...
}

//引用其他包中的类
payroll.Employee//使用类全名描述
import payroll.*;//用import关键字引入,使用通配符"*"
import payroll.Employee;//使用import关键字引入Employee类

//C++
#include <iostream>
using namespace std;//使用using namespace指令,这样在使用命名空间时就可以不用在前面加上命名空间的名称。
 
// 第一个命名空间
namespace first_space{
   void func(){
      cout << "Inside first_space" << endl;
   }
}
// 第二个命名空间
namespace second_space{
   void func(){
      cout << "Inside second_space" << endl;
   }
}
int main ()
{
   // 调用第一个命名空间中的函数
   first_space::func();
   // 调用第二个命名空间中的函数
   second_space::func(); 
   return 0;
}

//C#
using System;
namespace first_space{
   class namespace_cl{
      public void func(){
         Console.WriteLine("Inside first_space");
      }
   }
}
namespace second_space{
   class namespace_cl{
      public void func(){
         Console.WriteLine("Inside second_space");
      }
   }
}   
class TestClass{
   static void Main(string[] args){
      first_space.namespace_cl fc = new first_space.namespace_cl();
      second_space.namespace_cl sc = new second_space.namespace_cl();
      fc.func();
      sc.func();
      Console.ReadKey();
   }
}

接口(抽象类,协议)

public interface NameOfInterface{//接口定义
   //任何类型 final, static 字段
   //抽象方法
}
public interface Football extends Sports, Event//接口继承
public class MammalInt implements Animal//接口实现

//C++
class Shape{//类中至少有一个函数被声明为纯虚函数,则这个类就是抽象类
   public:      
      virtual int getArea() = 0;//提供接口框架的纯虚函数
};
class Rectangle: public Shape{//派生类
public:
   int getArea(){ //在派生类中重载纯虚函数
      return (width * height); 
   }
};

//C#
interface IParentInterface{//定义接口
    void ParentInterfaceMethod();
}

interface IMyInterface : IParentInterface{//接口继承
    void MethodToImplement();
}
class InterfaceImplementer : IMyInterface{//实现接口
    public void MethodToImplement(){
        Console.WriteLine("MethodToImplement() called.");
    }
    public void ParentInterfaceMethod(){
        Console.WriteLine("ParentInterfaceMethod() called.");
    }
}

//PHP
interface iTemplate{
    public function setVariable($name, $var);
}
class Template implements iTemplate{
    private $vars = array();
    public function setVariable($name, $var){
        $this->vars[$name] = $var;
    }
}

//Swift
protocol SomeProtocol {//协议定义
    // 协议内容
}
protocol InheritingProtocol: SomeProtocol, AnotherProtocol {//协议继承
    // 协议定义
}
class SomeClass: SomeSuperClass, FirstProtocol, AnotherProtocol {//协议实现,父类名放在协议名之前,以逗号分隔
    // 类的内容
}

//Go
type Phone interface {//定义接口
    call()
}
type IPhone struct {//定义结构体
}
func (iPhone IPhone) call() {//实现接口方法
    fmt.Println("I am iPhone, I can call you!")
}
func main() {
    var phone Phone		//定义接口变量
    phone = new(IPhone)	//变量赋值为IPhone
    phone.call()		//调用Iphone的call方法
}

枚举

public enum Color {//常量枚举
  RED, GREEN, BLANK, YELLOW  
} 

public enum Color {//有方法的枚举,有点像类了,都继承自java.lang.Enum类,可以实现接口
    RED("红色", 1), GREEN("绿色", 2), BLANK("白色", 3), YELLO("黄色", 4);//必须有;
    // 成员变量  
    private String name;  
    private int index;  
    // 构造方法  
    private Color(String name, int index) {  
        this.name = name;  
        this.index = index;  
    }  
    // 普通方法  
    public static String getName(int index) {  
        for (Color c : Color.values()) {  
            if (c.getIndex() == index) {  
                return c.name;  
            }  
        }  
        return null;  
    }  
    // get set 方法  
    public String getName() {  
        return name;  
    }  
    public void setName(String name) {  
        this.name = name;  
    }  
    public int getIndex() {  
        return index;  
    }  
    public void setIndex(int index) {  
        this.index = index;  
    }  
}  

public enum Singleton {//单例模式最佳方法,线程安全,支持序列化
    INSTANCE;  
    public void whateverMethod() {  
    }  
}

//C, C++
enum DAY{
      MON=1, TUE, WED, THU, FRI, SAT, SUN//默认从0开始,这样就从1开始了
} day;
day = WED;
printf("%d",day);

enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };
int WeekdayStart = (int)Days.Mon;

//可以遵守协议(protocols)来提供标准的功能。
//可以定义构造函数(initializers)来提供一个初始成员值
enum Student{//相关值枚举
    case Name(String)
    case Mark(Int,Int,Int)
}
var studDetails = Student.Name("Runoob")
var studMarks = Student.Mark(98,97,95)
switch studMarks {
case .Name(let studName):
    print("学生的名字是: \(studName)。")
case .Mark(let Mark1, let Mark2, let Mark3):
    print("学生的成绩是: \(Mark1),\(Mark2),\(Mark3)。")//学生的成绩是: 98,97,95。
}

enum Month: Int {//原始值枚举
    case January = 1, February, March, April, May, June//不会隐式地赋值为0,1,……和6
}
let yearMonth = Month.May.rawValue
print("数字月份为: \(yearMonth)。")//数字月份为: 5。

泛型

//Java(C++, C#, Swift也支持泛型,使用方式差不多)
public class MaximumTest{
   // 比较三个值并返回最大值,传入参数限制为Comparable类型
   public static <T extends Comparable<T>> T maximum(T x, T y, T z){//泛型方法
      T max = x; // 假设x是初始最大值
      if ( y.compareTo( max ) > 0 ){
         max = y; //y 更大
      }
      if ( z.compareTo( max ) > 0 ){
         max = z; // 现在 z 更大           
      }
      return max; // 返回最大对象
   }
   public static void main( String args[] ){
      System.out.printf( "%d, %d 和 %d 中最大的数为 %d\n\n",3, 4, 5, maximum(3, 4, 5));
      System.out.printf( "%.1f, %.1f 和 %.1f 中最大的数为 %.1f\n\n",6.6, 8.8, 7.7, maximum(6.6, 8.8, 7.7));
      System.out.printf( "%s, %s 和 %s 中最大的数为 %s\n","pe","ap", "or", maximum("pe", "ap", "or"));
   }
}
public class Box<T> {//泛型类   
  private T t; 
  public void add(T t) {
    this.t = t;
  } 
  public T get() {
    return t;
  } 
  public static void main(String[] args) {
    Box<Integer> integerBox = new Box<Integer>();
    Box<String> stringBox = new Box<String>();
 
    integerBox.add(new Integer(10));
    stringBox.add(new String("菜鸟教程"));
 
    System.out.printf("整型值为 :%d\n\n", integerBox.get());
    System.out.printf("字符串为 :%s\n", stringBox.get());
  }
}

public static void getData(List<?> data)//类型通配符一般是使用?代替具体的类型参数。例如 List<?> 在逻辑上是List<String>,List<Integer> 等所有List<具体类型实参>的父类

面向对象

//java
import java.io.*;//提供一个合理的路径,使得编译器可以找到某个类。
public interface Run{  
   	void run ();
} 
public interface Jump{  
   	void jump ();
} 
abstract class Animal {//抽象类,抽象类不能被实例化
  	void eat() {
    	System.out.println("Animal : 吃");
  	}
  	abstract void work(){}//抽象方法,抽象类中不一定包含抽象方法,但是有抽象方法的类必定是抽象类。
}
public class Dog extends Animal implements Run, Jump{//Animal是父类,Java不支持多继承父类,但可以多继承接口
   	int age;//成员变量
   	public Dog(String name){//构造方法
      	System.out.println("狗的名字是 : " + name ); 
   	}
   	public void setAge( int age ){//set方法
       age = age;
   	}
   	public int getAge( ){//get方法
       	System.out.println("狗的年龄为 : " + age ); 
       	return age;
   	}
  	public void eat() {//重写(Override),覆盖父类方法
    	System.out.println("Dog : 吃骨头");
  	}
  	public void eat(int a) {//重写(Override),方法名相同而参数不同
    	System.out.println("Dog : 吃骨头(a)");
  	}
   	public void run (){//实现Run接口方法
       	System.out.println("狗跑"); 
   	} 
   	public void jump (){//实现Jump接口方法
       	System.out.println("狗跳"); 
   	} 
   	public void work (){//重写抽象方法
       	System.out.println("看家"); 
   	} 
	void test(){
		this.eat();   // this 调用自己的方法
	    super.eat();  // super 调用父类方法
	}
	public static void main(String []args){//加static是类方法
      	Dog dog = new Dog("tommy");//创建对象
      	dog.setAge(2);//通过方法来设定age
      	dog.getAge();//调用另一个方法获取age
      	System.out.println("变量值 : " + dog.age ); //也可以这样访问成员变量

      	Animal a = new Dog("pubby");
      	a.eat();//虚拟方法(virtual),编译器使用Animal类中的eat()方法验证,运行的时候JVM调用的是Dog类中的eat()方法。
   	}
}

//C++
#include <iostream>
using namespace std;
class Dog{
   	public:
   		static int dogCount;//无论创建多少个类的对象,静态成员都只有一个副本。
   	 	Dog(string name){//构造函数
   	 		cout << "狗的名字是 : " + name << endl;
    		ptr = new int;
   		}
   		Dog( const Dog &obj){//拷贝构造函数
   		    cout << "调用拷贝构造函数并为指针 ptr 分配内存" << endl;
			    ptr = new int;
			    *ptr = *obj.ptr;//拷贝值
		}
   		~Dog(){  //析构函数,每次删除所创建的对象时执行
   		    cout << "释放内存" << endl;
    		delete ptr;
		}
		friend void printAge(Dog dog);//友元函数是定义在类外部,但有权访问类的所有私有(private)成员和保护(protected)成员。友元函数并不是成员函数。友元可以是函数(友元函数);可以是类(友元类),整个类及其所有成员都是友元。
		int getAge(){
			return age;
		}
		int getAge(int a);//重载
		int compare{Dog dog){
			return this->getAge() > dog.getAge();//对象通过this指针来访问自己的地址,是所有成员函数的隐含参数。友元函数没有this指针。访问指向类的指针的成员,需要使用成员访问运算符 ->
		}
		static int getCount(){//静态成员函数没有 this 指针,只能访问静态成员
         	return dogCount;
      	}
   	protected:
   	private: //默认私有
   		int age;
      	int *ptr;//成员变量
}
void Dog::run (){//成员函数可以定义在类定义内部,或者单独使用范围解析运算符::来定义
   	 		cout << "狗跑"<< endl;
} 

class B : protected A{//这种继承,A中的public方法,在B中是protected的

inline int Max(int x, int y)//内联函数(inline),一般都是1-5行的小函数,编译器会把该函数的代码副本放置在每个调用该函数的地方。在类定义中的定义的函数都是内联函数,即使没有使用 inline 说明符。

int Dog::dogCount = 0;//初始化类Dog的静态成员

Dog::getCount();//静态函数只要使用类名加范围解析运算符 :: 就可以访问。

class Rectangle: public Shape, public PaintCost//Rectangle(派生类)继承了Shape(基类),C++可以多继承
class Triangle: public Shape
Shape *shape; Rectangle rec(10,7); Triangle tri(10,5); shape=&rec; shape=&tri;//多态

//接口。如果类中至少有一个函数被声明为纯虚函数,则这个类就是抽象类。抽象类不能被用于实例化对象,它只能作为接口使用
virtual int area() = 0;//虚函数(virtual)。在派生类中重新定义,编译器不静态链接到该函数,调用时动态链接,或后期绑定。

Box operator+(const Box& b){//重载 + 运算符,用于把两个 Box 对象相加
   	Box box;
   	box.length = this->length + b.length;
   	return box;
}
Box3 = Box1 + Box2;//把两个对象相加,得到 Box3

//C#
using System;
namespace LineApplication{
	class Shape{}//基类
	public interface PaintCost{}//接口
   	class Line : Shape, PaintCost{
	   	private double length;// 线条的长度
	   	public Line(){  // 构造函数      
	      	Console.WriteLine("对象已创建");
	   	}
	   	~Line(){ //析构函数      
	      	Console.WriteLine("对象已删除");
	   	}
	   	public void setLength( double len ){
	      	length = len;
	   	}
	   	public double getLength(){
	      	return length;
	   	}
	   	static void Main(string[] args){//关键字 static 意味着类中只有一个该成员的实例
	      	Line line = new Line();
	      	// 设置线条长度
	      	line.setLength(6.0);
	      	Console.WriteLine("线条的长度: {0}", line.getLength());           
	   	}
	}
}
//多态、运算符重载与C++一样

//php5起
<?php
interface iTemplate{}//接口
class BaseClass implements iTemplate{//实现接口
	const constant = 'constant value';//类常量
   	function __construct() {//构造函数
       	print "In constructor\n";
       	$this->name = "MyDestructableClass";
   	}
   	function __destruct() {//析构函数
       	print "Destroying " . $this->name . "\n";
   	}
}
class SubClass extends BaseClass {//继承
    // inherits BaseClass's constructor
}
$obj = new BaseClass();// In BaseClass constructor
$obj = new SubClass();// In BaseClass constructor,In SubClass constructor

echo $classname::CONST_VALUE; // 自 PHP 5.3.0 起

public static $my_static = 'foo';//static 也可用于定义静态变量以及后期静态绑定

abstract protected function getValue();//抽象方法,强制要求子类定义这些方法

// 匿名类,使用了 PHP 7+ 后的代码
$util->setLogger(new class {
    public function log($msg){
        echo $msg;
    }
});
?>

//Swift
class mainClass {
    var no1 : Int // 局部存储变量
    init(no1 : Int) {//构造过程
        self.no1 = no1 // 初始化
    }
    deinit {//析构过程
    	// 执行析构过程
	}
    func show() {
        print("这是超类 SuperClass")
    }
}
class subClass : mainClass {//继承
    var no2 : Int // 新的子类存储变量
    init(no1 : Int, no2 : Int) {
        self.no2 = no2 // 初始化
        super.init(no1:no1) // 初始化超类
    }
    override func show() {//重写(Overriding),使用 final 关键字防止它们被重写。
        print("这是子类 SubClass")
    }
}