Share via


加法運算子 (+)

將某數值運算式的值與另一個運算式的值相加或是連結兩個字串。

expression1 + expression2

引數

  • expression1
    任何運算式。

  • expression2
    任何運算式。

備註

運算式的型別決定 + 運算子的行為。

If

然後

結果型別

兩邊的運算式都是字元

串連

String

兩邊的運算式都是數值

Add

numeric

兩邊的運算式都是字串

串連

String

一個運算式是字元,另一個是數值

Add

char

一個運算式為字元,另一個是字串

串連

String

一個運算式為數值,另一個是字串

串連

String

為了串連,數字會強制變為數值的字串表示,字元會當做長度為 1 的字串。 為了字元與數字的加法運算,字元會強制變為數值,然後將這個兩個數字相加。

注意事項注意事項

如果案例中沒有使用型別附註,則數值資料會儲存為字串。 請使用明確型別轉換或型別附註變數,以確定加法運算子 (+) 不會將數字視為字串,或將字串視為數字。

範例

以下範例說明加法運算子處理不同資料型別運算式的過程。

var str : String = "42";
var n : double = 20;
var c : char = "A";  // the numeric value of "A" is 65
var result;
result = str + str;  // result is the string "4242"
result = n + n;      // result is the number 40
result = c + c;      // result is the string "AA"
result = c + n;      // result is the char "U"
result = c + str;    // result is the string "A42"
result = n + str;    // result is the string "2042"
// Use explicit type coversion to use numbers as strings, or vice versa.
result = int(str) + int(str);    // result is the number 84
result = String(n) + String(n);  // result is the string "2020"
result = c + int(str);           // result is the char "k"

需求

1 版

請參閱

參考

加法設定運算子 (+=)

概念

運算子優先順序

運算子摘要

型別轉換