函数_c++

函数_c++

一 .局部对象

重新编写头文件,有助于集中修改函数接口
.obj即对象代码,使用分离式编译更方便

二 .传参

1.传指针

2.传引用

  • 引用之后就绑定了
  • 常量引用
int i=1;
const int &ii=i;
string str="have a nice day";
const string &str1=str;
  • string
//init
string str1(str);
string str2(size_t n,char a);
//运算
str+=str1;
//通过下标访问
cout<<str[1]<<str.at(2);
//函数
str.size();
str.length();

str.clear();
str,empty();

str.reverse(100);
str.resize(10,'\0');
str.resize(10);
  • vector和迭代器
//init
vector<int> vec;
//加入或删除成员
vec.push_back(val);
vec.pop_back();
vec.insert(pos,val);
vec.erase(pos);

vec,front();//返回第一个值的引用
vec.back//同理

vec.begin();//返回起始值的地址
vec.end()//同理
  • 迭代器
for(vec::iterator itr=vec.begin;itr!=vec.end;itr++)

三 .const限定

const int *p=1;
int *const p=1;

四 .传数组

1.简单数组

特别地,对于char *str,
while(*str)有效,但其他类型不一定,末尾的值不确定

&a[10];
//数组中的某一个元素
(&a)[10];
//整个数组

2.多维数组

int *p[10];
int (*p)[10];
void f(char **p,char *str[]);
//数组中含有10个元素

五 .含有可变形参的函数

  • initializer_list
void f(initializer_list<int> ls);
f({1,5,4});

六 .返回值

  • void中的return类似于break
  • 返回的是临时对象,副本
  • 不能返回临时对象,已被提前销毁
  • 返回引用可作为左值,其余不可

1.列表初始化返回值

vector<string> pro;
return ("have","a");

*main函数的返回值

2.返回数组指针

typedef int arrT[10];
arrT *f(int,double);

int(*f(int,double))[10];
auto f(int,double)->int (*)[10];
decltype(arrT) *arrPtr(int,double);

3.const和const_cast

f(const int a);
f(int a);
//对传入值没有要求

f(const int *p);
f(int *p);
//前者要求传入常量

const_cast<const int&>(b);
const_cast<int &>(b);

七 .函数重载

1.默认实参

void f(int a=1,int b=1);
f();
f(3);
//前面的变量不能留空

八.调试帮助

assert(0);
//终止程序
#define NDEBUG
//P216

九.函数指针

int f(int a,int b);
int (*p)(int a,int b)=f;
//f被默认为函数地址
p(1,2);
*p(1,2);
f(1,2);

typedef decltype(f) *p;
//给形如f的函数一个指向它的指针

int (*f(int,int))(int*,int,int);
//前者为返回值,后者为形参类型
auto f(int,int)->int(*)(int *,int);
using f=int(*)(int*,int);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值