#include <iostream> using namespace std; class Array { public: Array(unsigned int s) { size = s; num = 0; a = new int[s]; } virtual ~Array() { delete[] a; } virtual void add(int e) { if (num < size) { //**********found********** a[num] = e; num++; } } int get(unsigned int i) const { if (i < size) return a[i]; return 0; } protected: int *a; unsigned int size, num; }; class SortedArray : public Array { public: //**********found********** SortedArray(unsigned int s) : Array(s) { } virtual void add(int e) { if (num >= size) return; int i = 0, j; while (i < num) { if (e < a[i]) { for (j = num; j > i; j--) { //**********found********** a[j] = a[j - 1]; } //**********found********** a[i] = e; break; } i++; } if (i == num) a[i] = e; num++; } }; void fun(Array &a) { int i; for (i = 10; i >= 1; i--) { a.add(i); } for (i = 0; i < 10; i++) { cout << a.get(i) << ", "; } cout << endl; } int main() { Array a(10); fun(a); SortedArray sa(10); fun(sa); return 0; }
时间: 2023-07-23 10:24:16 浏览: 69
以下是将 C++ 代码转换为 Java 代码的示例:
```java
import java.util.Arrays;
class Array {
protected int[] a;
protected int size, num;
public Array(int s) {
size = s;
num = 0;
a = new int[s];
}
protected void finalize() throws Throwable {
super.finalize();
// Free the resources
if (a != null) {
Arrays.fill(a, 0);
a = null;
}
}
public void add(int e) {
if (num < size) {
a[num] = e;
num++;
}
}
public int get(int i) {
if (i < size) {
return a[i];
}
return 0;
}
}
class SortedArray extends Array {
public SortedArray(int s) {
super(s);
}
public void add(int e) {
if (num >= size) {
return;
}
int i = 0, j;
while (i < num) {
if (e < a[i]) {
for (j = num; j > i; j--) {
a[j] = a[j - 1];
}
a[i] = e;
break;
}
i++;
}
if (i == num) {
a[i] = e;
}
num++;
}
}
public class Main {
public static void fun(Array a) {
for (int i = 10; i >= 1; i--) {
a.add(i);
}
for (int i = 0; i < 10; i++) {
System.out.print(a.get(i) + ", ");
}
System.out.println();
}
public static void main(String[] args) {
Array a = new Array(10);
fun(a);
SortedArray sa = new SortedArray(10);
fun(sa);
}
}
```
请注意,在 Java 中,不需要使用 `using namespace std` 来导入命名空间,并且在 Java 中,没有虚函数表的概念,因此我们省略了 `virtual` 关键字。另外,Java 中没有析构函数,因此我们使用 `finalize()` 方法来释放资源。
阅读全文