Java & C++ 数组声明和使用语法对比

来源:互联网 发布:淘宝网贷口子 编辑:程序博客网 时间:2024/06/07 10:15

最近既要写Android程序,使用java,又要用C++做图像处理,基础知识学的不牢固,结果两种语法经常会混淆,尤其是这个数组的使用上。因此写一个博客,加深印象。
参考书籍:
《Ivor Horton’s Beginning Visual C++ 2010》(Ivor Horton 著;苏正泉 李文娟译);
《Thinking in Java 》(Bruce Eckel 著; 陈昊鹏著)。

the Array of C++

Arrays

An array is simply a number of memory locations called array elements or simply elements , each of which can store an item of data of the same given data type, and which are all referenced through the same variable name.
Individual items in an array are specifi ed by an index value which is simply an integer representing the sequence number of the elements in the array, the first having the sequence number 0 , the second 1 , and so on. You can also envisage(设想) the index value of an array element as being an offset from the first element in an array.

Declaring Arrays

declaration statement:

data-type arrayname[int ];

C++ 中数组的声明和普通变量的声明的方法基本相同,唯一的区别就是应该在紧跟数组名的方括号内指出数组元素的数量。例如:
int numStu[20];
如上的这个数组就可以用来存放20个int形式的学生的学号。

Initializing Arrays

C++中初始化数组可以简单的理解为有三种形式。举例如下

1.nt numStu[3]; 2.int numStu[3] = {41204041,41204043,41204044};3.int numStu[3] = {41204041};4.int numStu[] ={41204041,41204043,41204044};

第1个完全没有初始化数组,知识为数组名指向了一段内存位置,数组元素包含上次使用这些内存位置的程序遗留下来的值。
第2中和第3种是一种类型。只是第2个完全初始化,第3个部分初始化而已。初始化数组的的数值不能比数组的元素多,否则将会报错。如果少,即为部分初始化,那么列表中的初始值被分配给从第一个元素开始的连续元素。没有得到初始值的数组元素初始化为0。
第4种省略掉数组的长度,同时提供初始值,那么数组元素的数量就由指定的初始值的数量决定。如上面的第4个数组的数量就是3。

the Array of Java

Array

An array is simply a sequence of either objects or primitives that are all the same type and are packaged together under one identifier name.

Declaring Arrays

Java中数组的声明方法有两种:
1. datatype arrayname[];
2. datatype[] arrayname;
举例如下:
1.int numStu[];
2.int[] numStu;
第1种是沿袭C++ 的形式,但是一般更喜欢第2种,因为更符合“数据类型集合“的概念。

需要注意的是,Java编译器不允许指定数组的大小。因为声明数组的时候只是获得了这个数组的引用,但是并没有为数组对象本身分配内存空间。这和C++不同:C++在声明的时候就要指定数组的大小,并将数组名指向内存位置。正是因为这个原因,C++数组可以不用初始化就可以应用(虽然得到的数值完全是随机的),而Java数组在访问前必须要首先初始化,因为Java在数组初始化的时候才给数组对象分配内存空间。

Initializing Arrays

Java数组初始化有三种方法,直接举例说明
1.
(1)声明数组
(2)使用new创建新的数组(int 不是对象,不过可以使用new创建基本数据类型数组)
(3)创建对象并赋值给数组引用。

int a = new int[3];for(int i = 0; i < a.length; i++) {    a[i] = i;}

2.

Integer[] a = new Integer[]{    new Integer(1),    new Integer(2),    3,} 

3.

Integer[] a = {    new Integer(1),    new Integer(2),    3,}

注意:
1.第1种形式只能用于数组被定义处;而第2和第3中则可以用于任何位置,甚至在方法调用的内部。例如在Android程序中初始化Listview的Adapter时:

adapter=new lvButtonAdapter(this,list,R.layout.item_menu,new String[]{"image_id","name","imagebutton"},new int[]{R.id.ItemImage,R.id.ItemText1,R.id.button});listView.setAdapter(adapter);

最后,说明一下,在访问数组的时候,一旦访问过界,C/C++是不会报错的,但是我们得到的结果自然不是我们想要的;java则会报错,这样就会避免许多潜在的错误!

1 0