c++的輸入輸出
- 輸入
cin
- 輸出
cout
- 例子
#include <iostream>
using namespace std;
int main(){
int age;
cout << "請輸入年齡:" << endl;
cin >> age;
cout << "年齡是:" << age << endl;
}
extern
- extern 修飾符可用于c++中調用c函數的調用規范
比如在c++中想要調用c語言的函數,就需要使用 extren “C”聲明 - 例子
比如 聲明一個 c語言的函數
#ifndef sum_h
#define sum_h
int sum(int a, int b);
#include <stdio.h>
#endif /* sum_h */
#include "sum.h"
int sum(int a, int b){
return a + b;
}
在c++文件中
#include <iostream>
using namespace std;
extern "C" {
#include "sum.h"
}
int main(){
cout << "10 + 10 sum is " << sum(10, 10) << endl;
return 0;
}
輸出結果為:10 + 10 sum is 20
- 如果想要自己的c語言的函數,在c++環境中和c語言中都可以很方便的調用。可以這樣寫,在c的頭文件中
#ifndef sum_h
#define sum_h
#ifdef __cplusplus
extern "C"
{
#endif
int sum(int a, int b);
#ifdef __cplusplus
}
#endif
#include <stdio.h>
#endif /* sum_h */
函數重載
- 有時候,我們需要實現幾個類似的功能,只是某些細節不一樣,這樣的話我們就可以使用函數重載的功能,如
#include <iostream>
using namespace std;
void func(){
cout << "func()" << endl;
}
void func(int a){
cout << "func(int a)" << a << endl;
}
int main(){
func();
func(10);
return 0;
}
輸出結果為: func()
func(int a)10
- 默認賦值
void func(int a,int b = 10){
cout << "func(int a, B = 10) is" << a <<"," << b << endl;
}
func(10);
輸出結果:func(int a, B = 10) is20,10
如果出現多個參數默認賦值的情況,默認賦值需要從右到左