#include <iostream>
using namespace std; class BankAccount{ private:
double balance; public:
BankAccount(double openingBalance){//初始余额
balance = openingBalance;
} void deposit(double amount){//存钱
balance = balance + amount;
} void withraw(double amount){//取钱
balance = balance - amount;
} void display(){//查询余额
cout << "balance = " << balance << endl;
} }; int main()
{ BankAccount bc1();
BankAccount bc2 = bc1;
bc1.withraw(21.00);
bc2.withraw(21.00);
bc1.display();
bc2.display(); return ;
}

C++程序运行结果:

C++与java中的赋值操作符-LMLPHP

public class BankAccount {

    private double balance;

    public BankAccount(double openingBalance){
balance = openingBalance;
} public void deposit(double amount){
balance = balance + amount;
} public void withraw(double amount){
balance = balance - amount;
} public void display(){
System.out.println("balance = "+balance); } public static void main(String[] args) {
BankAccount bc1 = new BankAccount(200);
BankAccount bc2 = bc1;
bc1.withraw(21.00);
bc2.withraw(21.00);
bc1.display();
bc2.display();
} }

Java程序运行结果:

C++与java中的赋值操作符-LMLPHP

原因:在C++中

   BankAccount bc1(200);

   这句话创建了一个对象,并留出了所有这个对象数据的空间

   bc2 = bc1;

   是将bc1的对象的数据复制到bc2的对象里

   bc1与bc2的存储地址不同

   在Java中

   BankAccount bc1 = new BankAccount(200);

   该条语句仅创建了放置某一对象的存储地址的空间

   BankAccount bc2 = bc1;

   bc2复制了bc1指向的存储地址,实际上二者指的是同一个对象。类似于C++中的引用。

  

05-11 05:21