C++ Objective C Java C 详细比较和区别

本文深入对比了多种编程语言的关键特性,包括C++、Objective-C、Java、C#等,覆盖了从基本类型到高级功能的各个方面,为程序员选择合适的语言提供了全面的参考。

分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow

也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!

               

primitive types | arithmetic and logic | strings | regexes | dates and time | arrays | dictionaries | functions
execution control | files | directories | processes and environment | libraries and namespaces | objects | generic types
reflection | web | contact

c++ (1983)objective c (1986)java (1995)c# (2001)
hello word$ cat hello.cpp
#include <iostream>
using namespace std;
int main(int argc, char**arg) {
  cout << "Hello, World!" << endl;
}
$ g++ hello.cpp
$ ./a.out
Hello, World!
$ cat hello.m
#include <stdio.h>
int main(int argc, char **argv) {
  printf("Hello, World!\n");
}
$ gcc hello.m
$ ./a.out
Hello, World!
$ cat Hello.java
public class Hello {
  public static void main(String[] args) {
    System.out.println("Hello, World!");
  }
}
$ javac Hello.java
$ java Hello
Hello, World!
$ cat hello.cs
using System;
public class Hello {
  public static void Main() {
    Console.WriteLine("Hello, World!");
  }
}
$ mcs hello.cs
$ mono hello.exe
Hello, World!
version used
 
g++ 4.2gcc 4.2java 1.6mono 2.10 (C# 4.0)
version
 
$ g++ —version$ gcc —version$ javac -version$ mcs —version
libraries used
 
STL and BoostFoundation FrameworkJava APIBase Class Library
source, header, object file suffix.cpp .hpp .o.m .h .o.java none .class.cs none .exe or.dll
null
 
NULLNULLnullnull
printf
 
cout << "count: " << 7 << endl;printf("count: %d\n", 7);System.out.printf("count: %d", 7);System.Console.WriteLine("count: {0}", 7);
case and underscores in namesA_MACRO_NAME
AClassName
AMethodName() or a_method_name()
a_variable_name
A_MACRO_NAME
AClassName
[obj aMsgName:arg aLabelName:arg]
aVariableName
AClassName
aMethodName()
aVariableName
AClassName
AMethodName()
aVariableName
coalesce
 
string s1 = s2 || "was null";NSString *s1 = s2 || @"was null";String s1 = s2 == null ? "was null" : s2;string s1 = s2 ?? "was null";
primitive types
 c++objective cjavac#
declare primitive type on stackint i;
int j = 3;
int k(7);
int i;
int j = 3;
int i;
int j = 3;
int i;
int j = 3;
allocate primitive type on heapint *ip = new int;#include <stdlib.h>

int *ip = malloc(sizeof(int));
primitive types are always stack allocated. Use a wrapper class to store on the heap:
Integer i = new Integer(0);
object i = 0;
free primitive type on heapdelete i;#include <stdlib.h>

free(ip);
garbage collectedgarbage collected
value of uninitialized primitive typessame as C. However, C++ provides a no-argument constructor for each primitive type which zero-initializes it.stack variables and heap variables allocated with malloc have indeterminate values. Global and static variables and heap variables allocated with calloc are zero-initialized.zero-initializedcompiler prevents use of uninitialized variables in some circumstances, and zero-initializes in others
boolean types
 
boolBOOLbooleanbool
signed integer typessigned char 1+ byte
short int 2+ bytes
int 2+ bytes
long int 4+ bytes
long long int 4+ bytes
signed char 1+ byte
short int 2+ bytes
int 2+ bytes
long int 4+ bytes
long long int 4+ bytes
byte 1 byte
short 2 bytes
int 4 bytes
long 8 bytes
sbyte 1 byte
short 2 bytes
int 4 bytes
long 8 bytes
unsigned integer typesunsigned char: 8+
unsigned short int 2 bytes+
unsigned int 2 bytes+
unsigned long int 4+ bytes
unsigned long long int 4+ bytes
unsigned char: 8+
unsigned short int 2 bytes+
unsigned int 2 bytes+
unsigned long int 4+ bytes
unsigned long long int 4+ bytes
char 2 bytesbyte 1 byte
ushort 2 bytes
uint 4 bytes
ulong 8 bytes
floating point and decimal typesfloat
double
long double
float
double
long double
float 4 bytes
double 8 bytes
float 4 bytes
double 8 bytes
decimal 12 bytes
typedeftypedef int customer_id;
customer_id cid = 3;
typedef int customer_id;
customer_id cid = 3;
nonenone
enumenum day_of_week { mon, tue, wed, thu, fri, sat, sun };
day_of_week d = tue;
enum day_of_week { mon, tue, wed, thu, fri, sat, sun };
enum day_of_week d = tue;
public enum DayOfWeek { MON, TUE, WED, THU, FRI, SAT, SUN };
DayOfWeek d = DayOfWeek.TUE;
public enum DayOfWeek { MON, TUE, WED, THU, FRI, SAT, SUN };
DayOfWeek d = DayOfWeek.TUE;
arithmetic and logic
 c++objective cjavac#
true and false
 
true falseYES NOtrue falsetrue false
falsehoods
 
false 0 0.0 NULL0 0.0 NULLfalsefalse
logical operators&& || !
and or not
&& || !&& || !&& || !
relational operators== != < > <= >=== != < > <= >=== != < > <= >=== != < > <= >=
arithmetic operators
 
+ - * / %+ - * / %+ - * / %+ - * / %
division by zeroprocess sent a SIGFPE signalprocess sent a SIGFPE signalthrows java.lang.ArithmeticExceptionthrows System.DivideByZeroException
power#include <boost/math/special_functions.hpp>
boost::math::powm1<double>(2.0,3.0)+1
#include <math.h>

pow(2.0,3.0);
Math.pow(2.0,3.0);System.Math.Pow(2.0,3.0);
absolute value#include <stdlib.h>

int i = -7;
abs(i);
#include <math.h>
float x = -7.77;
fabs(x)
#include <stdlib.h>

int i = -7;
abs(i);
#include <math.h>
float x = -7.77;
fabs(x)
Math.abs(-7)
Math.abs(-7.77)
System.Math.Abs(-7)
System.Math.Abs(-7.77)
transcendental functions#include <math.h>

sqrt exp log log2 log10 sin cos tan asin acos atan atan2
#include <math.h>

sqrt exp log log2 log10 sin cos tan asin acos atan atan2
Math.sqrt Math.exp Math.log none Math.log10 Math.sin Math.cos Math.tan Math.asin Math.acos Math.atan Math.atan2using System;
 
Math.Sqrt Math.Exp Math.Log none Math.Log10 Math.Sin Math.Cos Math.Tan Math.Asin Math.Acos Math.Atan Math.Atan2
arithmetic truncation#include <math.h>
 
double d = 3.77;
 
long trunc = (long)d;
long rnd = round(d);
long flr = floorl(d);
long cl = ceill(d);
#include <math.h>
 
double d = 3.77;
 
long trunc = (long)d;
long rnd = round(d);
long flr = floorl(d);
long cl = ceill(d);
(long)3.77
Math.round(3.77)
(long)Math.floor(3.77)
(long)Math.ceil(3.77)
using System;
 
(long)3.77
Math.Round(3.77)
Math.Floor(3.77)
Math.Ceiling(3.77)
random integer#include <boost/random.hpp>
using namespace boost;
mt19937 rng;
uniform_int<> ui(0,RAND_MAX);
variate_generator<mt19937&, uniform_int<> > brand(rng, ui);
int i = brand()
#include <stdlib.h>

int i = rand();
java.util.Random r = new java.util.Random();
int i = r.nextInt();
System.Random r = new System.Random();
int i = r.Next();
bit operators<< >> & | ^ ~
bitand bitor comp
<< >> & | ^ ~ << >> & | ^ ~ << >> & | ^ ~
strings
 c++objective cjavac#
type
 
std::stringNSStringjava.lang.Stringstring
literal
 
none@"hello""don't say\"no\"""hello"
newline in literal?string literals can extend over multiple lines, but the newlines do not appear in the resulting stringstring literals can extend over multiple lines, but the newlines do not appear in the resulting stringnostring literals can extend over multiple lines, but the newlines do not appear in the resulting string
escapes
 
\a \b \f \n \r \t \v \xhh \\ \" \' \o \oo \ooo\a \b \f \n \r \t \v \xhh \\ \" \' \o \oo \ooo\b \f \n \r \t \uhhhh \\ \" \' \o \oo \ooo\a \b \f \n \r \t \v \xhh \xhhhh \\ \" \' \o \oo \ooo
allocate stringstring *s = new string("hello");NSString *s = @"hello";String s = "hello";
String t = new String(s);
string s = "hello";
string t = string.Copy(s);
length
 
s->length()[s length]s.length()s.Length
comparisonstring *s1 = new string("hello");
string *s2 = new stringt("world");
cout << s1->compare(*s2) << endl;
[@"hello" compare:@"hello"]"hello".compareTo("world")"hello".CompareTo("world")
semantics of ==value comparisonobject identity comparisonobject identity comparisonvalue comparison
to C string
 
s->c_str()[s UTF8String]nonenone
string to number#include <sstream>
stringstream ss("7 14.3 12");
int i;
double d;
long l;
ss >> i >> d >> l;
[@"14" integerValue]
[@"14" longLongvalue]
[@"14.7" floatValue]
[@"14.7" doubleValue]
Byte.parseByte("14")
Short.parseShort("14")
Integer.parseInt("14")
Long.parseLong("14")
Float.parseFloat("14.7")
Double.parseDouble("14.7")
byte.Parse("14")
short.Parse("14")
int.Parse("14")
long.Parse("14")
float.Parse("14")
double.Parse("14")
decimal.Parse("14")
number to string  Integer.toString(14)
Long.toString(14)
Double.toString(14.7)
14.ToString()
14.7.ToString()
split#include <boost/algorithm/string.hpp>
#include <vector>
string s("Bob Amy Ned");
vector<string> vec;
boost::split(vec, s, boost::is_any_of(" "));
[@"Bob Ned Amy" componentsSeparatedByString:@" "]"Bob Ned Amy".split(" ")string[] names = "Bob Ned Amy".Split(' ');
join
 
   System.String.Join(", ", names)
concatenatestring *s1 = new string("hello");
string *s2 = new string(" world");
cout << *s1 + *s2 << endl;
NSString *s1 = @"hello";
NSString *s2 = @" world";
NSString *s3 = [s1 stringByAppendingString:s2];
"hello" + " world""hello" + " world"
substringstring("hello").substr(2,2)[@"hello" substringWithRange:NSMakeRange(2,2)]"hello".substring(2,4)"hello".Substring(2,2)
index
 
string("hello").find("ll")[@"hello" rangeOfString:@"ll"].location"hello".indexOf("ll")"hello".IndexOf("ll")
sprintf#include <sstream>
ostringstream o('');
o << "Spain" << ": " << 7;
o.str();
[NSString stringWithFormat:@"%@: %d", @"Spain", 7]String.format("%s: %d", "Spain", 7)string.Format("{0}: {1}", "Spain", 7)
uppercase#include <boost/algorithm/string.hpp>
string s("hello");
boost::to_upper(s);
[@"hello" uppercaseString]"hello".toUpperCase()"hello".ToUpper()
lowercase#include <boost/algorithm/string.hpp>
string s("HELLO");
boost::to_upper(s);
[@"HELLO" lowercaseString]"HELLO".toLowerCase()"HELLO".ToLower()
trim#include <boost/algorithm/string.hpp>
string s(" hello ");
boost::trim(s);
[@" hello " stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]]" hello ".trim()" hello ".Trim()
pad on right [@"hello" stringByPaddingToLength:10 withString:@" " startingAtIndex:0]  
regular expressions
 c++objective cjavac#
regex match#include <boost/xpressive/xpressive.hpp>
using namespace boost::xpressive;
sregex re = sregex::compile(".*ll.*");
smatch matches;
string s("hello");
bool is_match = regex_match(s, matches, re);
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", @".*ll.*"];
BOOL is_match = [pred evaluateWithObject:@"hello"];
boolean isMatch = "hello".matches(".*ll.*");using System.Text.RegularExpressions;
Regex regex = new Regex("ll");
bool isMatch = regex.IsMatch("hello");
regex substitute#include <boost/xpressive/xpressive.hpp>
using namespace boost::xpressive;
string s("hello");
sregex re1 = as_xpr("ll");
string format1("LL");
string result1 = regex_replace(s, re1, format1, regex_constants::format_first_only);
sregex re2 = as_xpr("l");
string format2("L");
string result2 = regex_replace(s, re2, format2);
 String s1 = "hello".replace("ll","LL");
String s2 = "hello".replaceAll("l","L");
using System.Text.RegularExpressions;
Regex r1 = new Regex("ll");
String s1 = r1.Replace("hello", "LL", 1);
Regex r2 = new Regex("l");
String s2 = r2.Replace("hello", "L");
dates and time
 c++objective cjavac#
date/time type
 
  java.util.DateSystem.DateTime
current date/time  long millis = System.currentTimeMillis();
Date dt = new Date(millis);
DateTime dt = DateTime.Now();
to unix epoch, from unix epoch  long epoch = dt.getTimeInMillis()/1000;

Date dt2 = new Date(epoch * 1000);
long hundredM = 100*1000*1000;
long sec = dt.ToFileTimeUtc() / hundredM;
long epoch = sec - 1164444480;

long ft = (epoch + 1164444480) * hundredM;
Date dt2 = DateTime.FromFiltTimeUtc(ft);
strftime  String s = "yyyy-MM-dd HH:mm:ss";
DateFormat fmt = new SimpleDateFormat(s);
String s2 = fmt.format(dt);
String s = "yyyy-MM-dd HH:mm:ss");
String s2 = dt.ToString(s);
strptime  String s = "2011-05-03 17:00:00";
Date dt2 = fmt.parse(s);
CultureInfo enUS =
  new CultureInfo("en-US");

DateTime dt2 = DateTime.ParseExact(
  "2011-05-03 17:00:00",
  "yyyy-MM-dd HH:mm:ss",
  enUS);
arrays
 c++objective cjavac#
allocate array on stackint a[10];int a[10];arrays must be allocated on heaparrays must be allocated on heap
allocate array on heapint *a = new int[10];#include <stdlib.h>
int *a = calloc(10, sizeof(int));
int[] a = new int[10];int[] a = new int[10];
free array on heapdelete[] a;#include <stdlib.h>
free(a);
garbage collectedgarbage collected
array literalint a[] = {1,2,3};NSArray *a = [NSArray arrayWithObjects:@"hello", @"goodbye", nil];int[] a = {1,2,3};int[] a = {1,2,3};
array access
 
a[0][a objectAtIndex:0]a[0]a[0]
length
 
none[a count]a.lengtha.Length
array out-of-bounds resultundefined, possible SIGSEGVraises NSRangeException exceptionArrayIndexOutOfBoundsExceptionIndexOutOfRangeException
array iterationint a[10];
for (i=0; i<10; i++ ) {
  do something with a[i]
}
NSEnumerator *i = [a objectEnumerator];
id o;
while (o = [i nextObject]) {
  do something with o
}
for (String name : names) {foreach (string name in names) {
struct definitionclass MedalCount {
public:
  const char *country;
  int gold;
  int silver;
  int bronze;
};
struct medal_count {
  const char* country;
  int gold;
  int silver;
  int bronze;
};
public class MedalCount {
  public String country;
  public int gold;
  public int silver;
  public int bronze;
}
public class MedalCount {
  public string country;
  public int gold;
  public int silver;
  public int bronze;
}
struct declarationMedalCount spain;struct medal_count spain;MedalCount spain = new MedalCount();MedalCount spain = new MedalCount();
struct initializationMedalCount spain = { "Spain", 3, 7, 4 };struct medal_count spain = { "Spain", 3, 7, 4};
struct medal_count france = { .gold = 8, .silver = 7, .bronze = 9, .country = "France" };
no object literal syntax; define a constructorno object literal syntax; define a constructor
struct member assignmentspain.country = "Spain";
spain.gold = 3;
spain.silver = 7;
spain.bronze = 4;
spain.country = "Spain";
spain.gold = 3;
spain.silver = 7;
spain.bronze = 4;
spain.country = "Spain";
spain.gold = 3;
spain.silver = 7;
spain.bronze = 4;
spain.country = "Spain";
spain.gold = 3;
spain.silver = 7;
spain.bronze = 4;
struct member accessint spain_total = spain.gold + spain.silver + spain.bronze;int spain_total = spain.gold + spain.silver + spain.bronze;int spain_total = spain.gold + spain.silver + spain.bronze;int spain_total = spain.gold + spain.silver + spain.bronze;
vector declaration#include <vector>
vector <int> vec;
NSMutableArray *a = [NSMutableArray arrayWithCapacity:10];java.util.Vector<String> vec = new java.util.Vector<String>();using System.Collections.Generic;
List<string> l = new List<string>();
vector pushvec.push_back(7);[a addObject:@"hello"];vec.add("hello");
or
vec.add(vec.size(), "hello")
l.Add("hello");
vector pop
 
vec.pop_back();[a removeLastObject];vec.removeElementAt(vec.size()-1);l.RemoveAt(l.Count - 1);
vector size
 
vec.size()[a count]vec.size()l.Count
vector accessvec[0]
vec.at(0)
[a objectAtIndex:0]vec.elementAt(0)l[0]
vector out of bounds resultvec[] has undefined behavior
vec.at() raises out_of_range
raises NSRangeExceptionthrows ArrayIndexOutOfBoundsExceptionthrows System.ArgumentOutOfRangeException
vector iterationint sum = 0;
vector<int>::iterator vi;
for (vi = vec.begin(); vi != vec.end(); vi++ ) {
  sum += *vi;
}
NSEnumerator *i = [a objectEnumerator];
id o;
while (o = [i nextObject]) {
  do something with o
}
for ( String s : vec ) {
  do something with s
}
foreach ( string s in l ) {
  do something with s
}
dictionaries
 c++objective cjavac#
pairpair<int, float> p(7, 3.14);
cout << p.first << ", " << p.second << endl;
  using System.Collections.Generic;
KeyValuePair<string,int> pr = new KeyValuePair<string,int>("hello",5);
System.Console.WriteLine("{0} {1}", pr.Key, pr.Value);
map declaration#include <map>
map<string, int> m;
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:10];java.util.TreeMap<String, Integer> m = new java.util.TreeMap<String, Integer>();using System.Collections.Generic;
Dictionary<string, int> dict = new Dictionary<string, int>();
map accessm["hello"] = 5;
cout << m["hello"]) << endl;
[dict setObject:@"5" forKey:@"hello"];
[dict objectForKey:@"hello"]
m.put("hello", 5);
m.get("hello")
dict.Add("hello", 5);
dict["hello"]
map size
 
m.size()[dict count]m.size()dict.Count
map remove elementm.erase(m.find("hello"));[dict removeObjectForKey:@"hello"];m.remove("hello");dict.Remove("hello");
map element not found resultNULLNULLnullthrows KeyNotFoundException
in System.Collections.Generic
map iteratemap<string,int>::iterator mi;
for (mi = m.begin(); mi != m.end(); mi++) {
  printf("%s %d", mi->first, mi->second)
}
NSEnumerator *i = [dict keyEnumerator];
id key;
while ((key = [i nextObject])) {
  do something with key
}
for ( java.util.Map.Entry<String, Integer> e : m.entrySet() ) {
  use e.getKey() or e.getValue()
}
foreach ( KeyValuePair<string,int> e in dict) {
  use e.Key and e.Value
}
functions
 c++objective cjavac#
pass by valuevoid use_integer(int i) {
  function body
}
int i = 7;
use_integer(i);
void use_integer(int i) {
  function body
}
int i = 7;
use_integer(i);
primitive types are always passed by valueprimitive types are always passed by value
pass by addressvoid use_iptr(int *i) {
  function body
}
int i = 7;
use_iptr(&i);
void use_iptr(int *i) {
  function body
}
int i = 7;
use_iptr(&i);
nonenone
pass by referencevoid use_iref(int& i) {
printf("using iref: %d", i);
}
int i = 7;
use_iref(i);
noneobjects and arrays are always passed by referenceobjects and arrays are always passed by reference
default argument valuefloat log(float exp, float base=10.0) {noneuse method overloadinguse method overloading
named parametersnone+(float)weight: (float) w height: (float) h {
  return (w * 703) / (h * h);
}
+(float)height: (float) h weight: (float) w {
  return [BMI weight: w height: h];
}
[BMI weight:155 height:70];
[BMI height:70 weight:155];
noneadded in C# 4.0:
static int BMI(int weight, int height) {
  return (weight * 703) / (height * height);
}
BMI(weight: 123, height: 64);
BMI(height: 64, weight: 123);
function overloadingyesmethod overloading onlyyesyes
variable number of arguments
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值