c语言重载输入输出函数,c++ 入门 - 函数重载,extern

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

如果出现多个参数默认赋值的情况,默认赋值需要从右到左

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值