C/C++ 指针与 Java 引用
指针
在 C、C++ 编程语言中,指针是指向另一个变量地址的变量。
示例
#include <iostream>
using namespace std;
int main() {
//int variable
int i = 8;
//pointer variable
int * pI;
//assign the address of i to its pointer
pI = &i;
//print the number
cout<<i<<endl;
//print the address of the number
cout<<pI<<endl;
//print the value pointed by pointer
count<<*pI<<endl;
//change the value of variable using its pointer
*pI = 10;
//print the number
cout<<i<<endl;
}输出
8 0x7fee1ae7bc94 8 10
引用
在 java 编程语言中,引用是引用对象的变量,使用它我们可以利用对象的属性和功能。
示例
public class Tester {
public static void main(String[] args) {
Student student = new Student();
student.setName("Mahesh");
System.out.println(student.getName());
}
}
class Student {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}输出
Mahesh
指针和引用的区别
以下是 C/C++ 指针和引用的部分区别。
Java 中没有指针运算。指针是存储地址,并且指针指向变量的存储地址。在 C/C++ 中,可以增加/减少指针指向新地址,但在 Java 中,不允许对引用进行算术运算。
Java 中没有指针操作。 尽管引用在内部使用指针,但 Java 不允许使用引用变量对底层指针进行任何操作。它使 Java 更安全、更健壮。引用只能引用一个对象或为空。
Java 中没有指针类型转换。在 C/C++ 中,我们可以将 int* 转换为 char*,但在 Java 中,只有相关的对象可以进行类型转换,例如同一层次结构的对象。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP