对于 C++ 来说,将对象赋值给另一个对象变量,实际上相当于拷贝了一个对象副本给那个对象变量,所以此时如果修改对象变量的属性的话,将不会影响到原始对象的状态。
对于 Java 来说,将对象赋值给另一个对象变量,实际上相当于将对象的引用赋值给那个对象变量 ,所以此时如果修改对象变量的属性的话,将会影响到原始对象的状态。
C++:
#include <iostream>
class Student
{
public:
Student();
~Student();
int getAge();
void setAge(int age);
private:
int age;
};
// ***** 类的实现 *****
Student::Student(){}
Student::~Student() {};
int Student::getAge() {
return age;
}
void Student::setAge(int age) {
this->age = age;
}
// *******************
int main()
{
Student stu1;
stu1.setAge(16);
Student stu2 = stu1;
stu2.setAge(18);
// 此时 stu2.getAge() 返回的值为 18
printf("the age of stu2 is %d", stu2.getAge());
// 此时 stu1.getAge() 返回的值为 16,可见 stu1 将副本赋值给了 stu2,
// 所以对 stu2 的修改并不会影响到 stu1
printf("the age of stu1 is %d", stu1.getAge());
}
Java:
class Student{
private int age;
public int getAge() {
return age;
}
public void setAge(int age){
this.age=age;
}
}
class Test {
public static void main(String[] args) {
Student stu1=new Student();
stu1.setAge(16);
Student stu2=stu1;
stu2.setAge(18);
// 此时 stu2.getAge() 返回的值为 18
System.out.println("the age of stu2 is "+stu2.getAge());
// 此时 stu1.getAge() 返回的值也是 16,可见 stu1 将引用赋值给了 stu2,
// 所以对 stu2 的修改将会影响到 stu1
System.out.println("the age of stu1 is "+stu1.getAge());
}
}