C++、Java语法差异对照表

C++ and Java Syntax Differences Cheat Sheet



First, two big things--the main function and how to compile it, followed by lots of little differences.

main function  主函数

C++

// free-floating function
int main( int argc, char* argv[])
{
printf( "Hello, world" );
}

Java

// every function must be part of a class; the main function for a particular
// class file is invoked when java <class> is run (so you can have one
// main function per class--useful for writing unit tests for a class)
class HelloWorld
{
public static void main(String args[])
{
System.out.println( "Hello, World" );
}
}

Compiling编译与执行过程

C++

    // compile as
g++ foo.cc -o outfile
// run with
./outfile

Java

    // compile classes in foo.java to <classname>.class
javac foo.java // run by invoking static main method in <classname>
java <classname>

Comments 注释

Same in both languages (// and /* */ both work)

Class declarations 类的声明

Almost the same, but Java does not require a semicolon

C++

    class Bar {};

Java

    class Bar {}

Method declarations  方法的声明

Same, except that in Java, must always be part of a class, and may prefix with public/private/protected

Constructors and destructors  构造函数与析构函数

Constructor has same syntax in both (name of the class), Java has no exact equivalent of the destructor

Static member functions and variables 静态函数和变量

Same as method declarations, but Java provides static initialization blocks to initialize static variables (instead of putting a definition in a source code file):

class Foo
{
static private int x;
// static initialization block
{ x = 5; }
}

Scoping static methods and namespaces  静态方法作用域、命名空间

C++

If you have a class and wish to refer to a static method, you use the form Class::method.

class MyClass
{
public:
static doStuff();
}; // now it's used like this
MyClass::doStuff();

Java

All scoping in Java uses the . again, just like accessing fields of a class, so it's a bit more regular:

class MyClass
{
public static doStuff()
{
// do stuff
}
} // now it's used like this
MyClass.doStuff();

Object declarations  对象声明

C++

    // on the stack
myClass x; // or on the heap
myClass *x = new myClass;

Java

    // always allocated on the heap (also, always need parens for constructor)
myClass x = new myClass();

Accessing fields of objects  访问对象域

C++

If you're using a stack-based object, you access its fields with a dot:

myClass x;
x.my_field; // ok

But you use the arrow operator (->) to access fields of a class when working with a pointer:

myClass x = new MyClass;
x->my_field; // ok

Java

You always work with references (which are similar to pointers--see the next section), so you always use a dot:

myClass x = new MyClass();
x.my_field; // ok

References vs. pointers  引用与指针

C++

    // references are immutable, use pointers for more flexibility
int bar = 7, qux = 6;
int& foo = bar;

Java

    // references are mutable and store addresses only to objects; there are
// no raw pointers
myClass x;
x.foo(); // error, x is a null ``pointer'' // note that you always use . to access a field

Inheritance  继承

C++

    class Foo : public Bar
{ ... };

Java

    class Foo extends Bar
{ ... }

Protection levels (abstraction barriers) 保护级别(抽象屏障)

关于抽象的一个形象的隐喻(- - !),把抽象比喻成竖起一道屏障。


C++

    public:
void foo();
void bar();

Java

    public void foo();
public void bar();

Virtual functions 虚函数

C++

    virtual int foo(); // or, non-virtually as simply int foo();

Java

    // functions are virtual by default; use final to prevent overriding
int foo(); // or, final int foo();


Abstract classes 抽象类

C++

    // just need to include a pure virtual function
class Bar { public: virtual void foo() = 0; };

Java

    // syntax allows you to be explicit!
abstract class Bar { public abstract void foo(); } // or you might even want to specify an interface
interface Bar { public void foo(); } // and later, have a class implement the interface:
class Chocolate implements Bar
{
public void foo() { /* do something */ }
}


Memory management 内存管理

Roughly the same--new allocates, but no delete in Java since it has garbage collection.

NULL vs. null

C++

    // initialize pointer to NULL
int *x = NULL;

Java

    // the compiler will catch the use of uninitialized references, but if you
// need to initialize a reference so it's known to be invalid, assign null
myClass x = null;


Booleans 布尔值
Java is a bit more verbose(冗长的): you must write boolean instead of merely bool.

C++

bool foo;

Java

boolean foo;


Const-ness(常量性)

C++

    const int x = 7;

Java

    final int x = 7;


Throw Spec 异常检测

First, Java enforce throw specs at compile time--you must document if your method can throw an exception

C++

int foo() throw (IOException)

Java

int foo() throws IOException


Arrays 数组

C++

    int x[10];
// or
int *x = new x[10];
// use x, then reclaim memory
delete[] x;

Java

    int[] x = new int[10];
// use x, memory reclaimed by the garbage collector or returned to the
// system at the end of the program's lifetime

Collections and Iteration 集合类与迭代

C++

Iterators are members of classes. The start of a range is <container>.begin(), and the end is <container>.end(). Advance using ++ operator, and access using *.

    vector myVec;
for ( vector<int>::iterator itr = myVec.begin();
itr != myVec.end();
++itr )
{
cout << *itr;
}

Java

Iterator is just an interface. The start of the range is <collection>.iterator, and you check to see if you're at the end with itr.hasNext(). You get the next element using itr.next() (a combination of using ++ and * in C++).

    ArrayList myArrayList = new ArrayList();
Iterator itr = myArrayList.iterator();
while ( itr.hasNext() )
{
System.out.println( itr.next() );
} // or, in Java 5
ArrayList myArrayList = new ArrayList();
for( Object o : myArrayList ) {
System.out.println( o );
}

源地址: http://www.cprogramming.com/tutorial/java/syntax-differences-java-c++.html

C++、Java语法差异对照表的更多相关文章

  1. React Native之ES5/ES6语法差异对照表

    很多React/React Native的初学者都被ES6的问题迷惑:各路大神都建议我们直接学习ES6的语法(class Foo extends React.Component),然而网上搜到的很多教 ...

  2. C#与Java的语法差异

    C#与Java的语法差异C与Java的语法差异前言程序结构基本语法数据类型字符串变量与常量运算符判断语句循环语句访问权限方法数组结构枚举类继承多态运算符重载接口命名空间预处理器指令正则表达式异常IO泛 ...

  3. Kotlin VS Java:基本语法差异

    Kotlin比Java更年轻,但它是一个非常有前途的编程语言,它的社区不断增长. 每个人都在谈论它,并说它很酷. 但为什么这么特别? 我们准备了一系列文章,分享我们在Kotlin开发Android应用 ...

  4. php与java语法的区别

    php与java语法的区别 个人觉得在学习语言时,可以通过比较来进行学习.由于长时间写java代码,对java的基本语法还算熟悉,现在转学php,就php中基本语法与java基本语法差异进行比较. 1 ...

  5. php语法同java语法的基本区别(实例项目需求,php才能熟)

    php语法同java语法的基本区别(实例项目需求,php才能熟) 一.总结 看下面 二.PHP基本语法以及和Java的区别 .表示字符串相加 ->同Java中的. $作为变量的前缀,除此之外,变 ...

  6. Java语法

    java语法: 一个java程序可以说是一系列对象的集合,而这些对象都要通过调用彼此的方法来协同工作. 对象: 对象是一个实例,例如:一只猫,它是一个对象,有状态和行为.它的状态状态有:颜色,名字,品 ...

  7. Java语法糖1:可变长度参数以及foreach循环原理

    语法糖 接下来几篇文章要开启一个Java语法糖系列,所以首先讲讲什么是语法糖.语法糖是一种几乎每种语言或多或少都提供过的一些方便程序员开发代码的语法,它只是编译器实现的一些小把戏罢了,编译期间以特定的 ...

  8. Sqlite基础及其与SQLServer语法差异

    1 TOP 这是一个大家经常问到的问题,例如在SQLSERVER中可以使用如下语句来取得记录集中的前十条记录: SELECT TOP 10 * FROM [index] ORDER BY indexi ...

  9. 程序员带你学习安卓开发,十天快速入-对比C#学习java语法

    关注今日头条-做全栈攻城狮,学代码也要读书,爱全栈,更爱生活.提供程序员技术及生活指导干货. 如果你真想学习,请评论学过的每篇文章,记录学习的痕迹. 请把所有教程文章中所提及的代码,最少敲写三遍,达到 ...

随机推荐

  1. 数据库和Content Provider

    SQLite提供了强大的SQL数据库的库文件,从而使应用程序拥有一个具备完全控制权的健壮的持久化层. Content Provider实现在应用程序内和应用程序之间存储.共享和使用结构化数据.通过将数 ...

  2. FTP连接虚拟主机响应220 Welcome to www.net.cn FTP service. (解决的一个问题)

    问题场景: 使用FTP客户端连接虚拟主机时,同样的账号密码在有的网络下可以连接成功,有的网络下却一直连接不上:ftp响应“220 Welcome to www.net.cn FTP service.” ...

  3. 使用handler倒计时

    package com.example.jikangwang.myapplication; import android.content.Intent; import android.os.Handl ...

  4. REM——适合移动开发的自适应方案

    文章目录 1.什么是REM 2.REM和EM的区别 3.手机端方案的特点 4.使用JS动态调整REM 5.REM与其他单位同时存在 1.什么是REM 先来认识几个常见单位: px:像素,这个大家都知道 ...

  5. 初次部署django+gunicorn+nginx

    初次部署django+gunicorn+nginx  博客详细地址  https://www.cnblogs.com/nanrou/p/7026802.html 写在前面,这只是我所遇到的情况,如果有 ...

  6. 10-HTTPServletReauest和HTTPServletResponse

    Servlet配置方式 1. 全路径匹配 以 / 开始 /a /aa/bb localhost:8080/项目名称/aa/bb 2. 路径匹配 , 前半段匹配 以 / 开始 , 但是以 * 结束 /a ...

  7. 基于用户协同过滤--UserCF

    UserCF  本系列文章主要介绍推荐系统领域相关算法原理及其实现.本文以项亮大神的<推荐系统实践>作为切入点,介绍推荐系统最基础的算法(可能也是最好用的)--基于用户的协同过滤算法(Us ...

  8. h5、css3基础

    一.html(超文本标记语言) 作用:实现页面布局 页面由许多标记符号组成 由浏览器解释执行 二.html主题创建方式 !(英文状态)+tab html:4s+tab html:5+tab 三.标签 ...

  9. HBase MVCC 机制介绍

    关键词:MVCC HBase 一致性 本文最好结合源码进行阅读 什么是MVCC ? MVCC(MultiVersionConsistencyControl , 多版本控制协议),是一种通过数据的多版本 ...

  10. Ubuntu出现卡logo、卡住、黑屏无法正常启动、屏幕和键盘背光无法调节等一系列问题?可能是NVIDIA显卡驱动没装好

    也不知道是幸运还是不幸,我从一开始接触ubuntu就遇到这一系列的问题, 而且一直没有一个彻底解决的办法,搞得我无比头疼,也害得我重装了无数遍系统... 国际惯例,只按照个人习惯和喜好来写,对某些人来 ...