等於(=)這個符號的概念一直都是把左邊的值賦予給右邊的值
例如:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
int main() | |
{ | |
int a = 1; | |
int b = 2; | |
a = b; | |
b = 3; | |
cout<<"a = "<<a<<endl; | |
return 0; | |
} |
int a = 1;
int b = 2;
a = b; //b的值2給了a
b = 3; //之後值3給了b
結果a印出來是2, b是3
但是在java中,物件的等於是有pointer的含意在的,
假設我封裝了int的物件專門存int
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Int { | |
int value; | |
public Int(int value){ | |
this.value = value; | |
} | |
public void setInt(int value){ | |
this.value = value; | |
} | |
public int getInt(){ | |
return value; | |
} | |
} |
Int A = new Int(1);
Int B = new Int(2); A = B; //B被指定的new Int(2)的這個物件,指定給A控制
B.setInt(3);//B被指定的new Int(2)的這個物件,現在值3給了這個物件,A擁有這個物件所以值也變成3,b也是3
以下是java程式碼以供比較,基本上值的等於用法跟C++一樣沒變,只有物件不一樣要注意
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.Console; | |
class Demo { | |
public static void main(String[] args) { | |
int a = 1; | |
int b = 2; | |
a = b; | |
b = 3; | |
System.out.println("int結果"+a); | |
Int A = new Int(1); | |
Int B = new Int(2); | |
A = B; | |
B.setInt(3); | |
System.out.println("int物件結果"+a.getInt()); | |
} | |
} |
還有C++版本
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
int main() | |
{ | |
int a = 1; | |
int b = 2; | |
a = b; | |
b = 3; | |
cout<<"a = "<<a<<endl; | |
return 0; | |
} |
沒有留言:
張貼留言