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

news/2024/7/20 12:21:21 标签: java, c/c++, 内存管理

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

By Alex Allain

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



转载于:https://www.cnblogs.com/enjoy233/p/10408787.html


http://www.niftyadmin.cn/n/1667249.html

相关文章

告诉大家一些你不知道的Dubbo 但是很好用的功能

dubbo功能非常完善&#xff0c;很多时候我们不需要重复造轮子&#xff0c;下面列举一些你不一定知道&#xff0c;但是很好用的功能&#xff1b; 直连Provider 在开发及测试环境下&#xff0c;可能需要绕过注册中心&#xff0c;只测试指定服务提供者&#xff0c;这时候可能需要…

微信小程序----折叠面板(MUI折叠面板)

微信小程序----折叠面板&#xff08;MUI折叠面板&#xff09; DEMO下载 实现原理 通过控制详情部分的显示隐藏&#xff0c;来实现折叠效果&#xff0c;同时切换右侧向下箭头。 效果图 WXML <!--pages/accordion/accordion.wxml--> <view class"tui-accordion-co…

[转载]新版phpjm解密程序,也适用于其他混淆加密的破解

[转载]新版phpjm解密程序&#xff0c;也适用于其他混淆加密的破解 原文地址&#xff1a;新版phpjm解密程序&#xff0c;也适用于其他混淆加密的破解作者&#xff1a;chenshuanj已经全部公布&#xff1a;http://blog.sina.com.cn/s/blog_438310d50101eceo.html<?php$file …

20Spring_JdbcTemplatem模板工具类

JdbcTemplate 是Spring提供简化Jdbc开发模板工具类。为了更好的了解整个JdbcTemplate配置数据库连接池的过程&#xff0c;这篇文章不采用配置文件的方式&#xff0c;而是采用最基本的代码 的方式来写。后一篇文章会讲配置文件的方式。 1.Spring 对一下的持久层技术支持 2.jdbcT…

2020 最新java面试题附答案

以下面试题为个人在面试过程中所遇到的&#xff0c;仅供参考&#xff01;如有错误&#xff0c;望指出。 1、servlet执行流程 客户端发出http请求&#xff0c;web服务器将请求转发到servlet容器&#xff0c;servlet容器解析url并根据web.xml找到相对应的servlet&#xff0c;并…

[转载]nginx配置结合iptables防御ddos攻击方法

[转载]nginx配置结合iptables防御ddos攻击方法 原文地址&#xff1a;nginx配置结合iptables防御ddos攻击方法作者&#xff1a;残淡的梦一.nginx配置nginx配置指导文章http://hxl2009.blog.51cto.com/779549/1324473配置方法1、在nginx.conf里的http{}里加上如下代码&#xff1…

经典问题:代码中如何去掉烦人的“!=null判空语句

问题 为了避免空指针调用&#xff0c;我们经常会看到这样的语句 if (someobject ! null) { someobject.doCalc();} 最终&#xff0c;项目中会存在大量判空代码&#xff0c;多么丑陋繁冗&#xff01;如何避免这种情况&#xff1f;我们是否滥用了判空呢&#xff1f; 回答 …

关于DDOS攻击

关于DDOS攻击 http://www.abcde.cn/newscontent/20170830-ats.html相信各大建站企业最怕的就是被DDOS攻击了&#xff0c;DDOS攻击并不可怕&#xff0c;但是很多企业都不足够了解DDOS攻击&#xff0c;以为只要加以防范就可以高枕无忧了&#xff0c;这种想法是错误的。下面就梳理…