C/C++—— 一個特別奇怪的C++程式

readyao發表於2016-04-01

你認為下面這個程式會輸出什麼?


#include <iostream>
#include <string>
using namespace std;

string mostImportantOrders = "DO NOT LAUNCH THE MISSLES!";
void appendFour(int s) {
    cout << s + "4" << endl;
}

int main() {
    cout << "The total number of missiles is:" << endl;
    appendFour(44);
    cout << endl;
    return 0;
}










輸出結果。。卻是。。

The total number of missiles is:
NOT LAUNCH THE MISSLES!


目前確實是沒搞明白為什麼會輸出這樣。。感覺和string構造物件機制有關,並且也和cout輸出物件機制有關。



將上面的程式該為下面的程式:

#include <iostream>
#include <string>
using namespace std;

string mostImportantOrders = "DO NOT LAUNCH THE MISSLES!";
void appendFour(int s) {
    cout << s + '4' << endl;
}

int main() {
    cout << "The total number of missiles is:" << endl;
    appendFour(44);
    cout << endl;
    return 0;
}


輸出如下:

The total number of missiles is:
96


其中44+'4' = 44 + 4 + 48 = 96;








相關文章