c++的输入输出
输入
cin
输出
cout
例子
#include
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
#endif /* sum_h */
#include "sum.h"
int sum(int a, int b){
return a + b;
}
在c++文件中
#include
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
#endif /* sum_h */
函数重载
有时候,我们需要实现几个类似的功能,只是某些细节不一样,这样的话我们就可以使用函数重载的功能,如
#include
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 <
}
func(10);
输出结果:func(int a, B = 10) is20,10
如果出现多个参数默认赋值的情况,默认赋值需要从右到左