函式宣告與定義
函式宣告(declaration)
沒有程式碼,最後面有冒號;
告知編譯器有一個函式名字為print,傳回值型態為void,參數類型有int與const string&,之後會有程式碼實作。
void print(int code,const string& msg);
函式定義(definition)
有程式碼。
1
2
3
void print(int code, const string& msg) {
cout << "Error code = " << code << " , Msg = " << msg << endl;
}
呼叫函式
print(500, "Server Error.");
函式宣告與函式定義
1
2
3
4
5
6
7
8
9
10
11
//函式宣告
void print(int code,const string& msg);
int main() {
//呼叫函式
print(500, "Server Error.");
return 0;
}
//函式定義
void print(int code, const string& msg) {
cout << "Error code = " << code << " , Msg = " << msg << endl;
}
Error code = 500 , Msg = Server Error.
函式宣告與定義合在一起
在main()主程式前宣告函式,並且實作程式碼,就是函式宣告與定義結合一起,有實作程式碼一律稱之函式定義。
1
2
3
4
5
6
7
8
//函式定義
void print(int code, const string& msg) {
cout << "Error code = " << code << " , Msg = " << msg << endl;
}
int main() {
print(500, "Server Error.");
return 0;
}
Error code = 500 , Msg = Server Error.