函数定义
#include<iostream>
using namespace std;
class Date
{
};
void process()//void这是没有参数的函数
{
}
bool is_present(int * x, int y);
Date& calendar(const char * s);
//x的y次方 形参
int power(int x, int y)//这是一个函数
{
int result = 1;
for (int loop = 1;loop <= y;++loop)//(;;)
result *= x;
return result;
}
//绝对值
int abs(int x1)//这是一个函数定义
{
return x1 >= 0 ? x1 : -x1;
}
//最大公约数
int gcd(int v1, int v2)//这是一个函数
{
while (v2)
{
int temp = v2;
v2 = v1 % v2;
v1 = temp;
}
return v1;
}
int main()//这是一个函数
{
//函数调用 使用小括号和括号里的参数
cout << gcd(15, 123) << endl;//15,123为实参
cout << abs(-99) << endl;
cout << power(2,4) << endl;
return 0;
}
非引用形参
#include<iostream>
using namespace std;
void AddOne(int x)//非引用形参(即copy)中普通形参
{
x = x + 1;//把copy加1
};
void AddTwo(int *pt)//非引用形参中 指针形参
{
*pt = *pt + 2;
};
void AddThree(int& y)//引用形参
{
y = y + 3;//真正的加3
};
int main()
{
int a, b, c;
a = 1;
b = 2;
c = 3;
cout << "加之前:" << a << endl;
//并没有真正的a传进去,传的是a的copy
AddOne(a);
cout << "加之后:" << a << endl;
cout << "加之前:" << b << endl;
//把b 的地址copy一个传进去
AddTwo(&b);//&b 不是b
cout<<"加之后:"<<b<< endl;
cout << "加之前:" << c << endl;
//传的是真正的c 不是copy
AddThree(c);
cout << "加之后:" << c << endl;
return 0;
}
```非引用参数中参数的注意事项
```cpp
#include<iostream>
using namespace std;
int add(int x, int y)
{
return x + y;
}
int add_2(const int a, const int b)//不要少了int
{
return a + b;//不用加const int 只读const int 参数
}
void addOne(const int x)
{
//x = x + 1;//报错 因为是const int参数传进来就不能改了
}
int main()
{
int a, b;//普通非 const 变量
const int m = 8;//const 变量
const int n = 4;
a = 1;
b = 2;
/*int k = add(a, b);
cout << k << endl;
k = add(m, n);
cout << k << endl;
*/
int k = add_2(a, b);//非const 参数可以传给const int 参数
cout << k << endl;
k = add_2(m, n);
cout << k << endl;
return 0;
}
带指针的非形参函数
#include<iostream>
//指针的初始化规则 --可以将指向const对象的指针指向非const对象 反之不可
using namespace std;
void AddOne(int* pt)
{
*pt = *pt + 1;
}
void AddTwo(const int* pt)
{
//*pt = *pt + 2;
}
int add(const int *px, const int *py)//这里返回int 不是void
{
return *px + *py;
}
//下面的例子说明 当参数类型不同时 函数名可以一样(函数重改)
void fcn(int i)//const int 和int 认为是一样的 不可一样的函数名
{
cout << i << endl;
}
void fcn(double i)
{
cout << i << endl;
}
int main()
{
int a, b, c;
a = 1, b = 2, c = 3;
const int a1 = 5;
const int a2 = 6;
const int a3 = 7;
AddOne(&a);
add(&a, &b);
//AddOne(&a1);不能把const int * 传 非const int *
AddTwo(&a);
cout << "hello world" << endl;
}
非引用形参 参数传递
#include<iostream>
using namespace std;
int getBigger(int x,const int* y)
{
return x > * y ? x : *y;
}
/*
void swap(int x, int y)//交换copy
{
int temp;
temp = x;
x = y;
y = temp;
}
*/
void swap(int* x, int* y)//指针形式 就是交换了
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
int main()
{
int a = 2,b = 9;
cout << getBigger(a, &b) << endl;
cout << "交换之前" << a <<","<< b << endl;
//swap(a, b);
swap(&a, &b);
cout << "交换之后" <<a<<","<<b << endl;
return 0;
}
引用形参
#include<iostream>
// 非引用形参 -复制形参
using namespace std;
void swap(int &v1, int &v2)
{
int temp;
temp = v2;
v2 = v1;
v1 = temp;
}
void AddOne(int x)
{
x = x + 1;
}
void AddTwo(int& x)
{
x = x + 2;
}
int main()
{
int i = 10;
int j = 20;
cout << "Before swap():" << i << "," << j << endl;
//把i,j复制(copy)传递进去
swap(i, j);
cout << "After swap():" << i << "," << j << endl;
cout << "Before AddOne():" << i << endl;
//把i复制(copy)传递进去 加的copy 对原来的i没有影响
AddOne(i);
cout << "After AddOne():" << i << endl;
cout << "Before AddTwo():" << i << endl;
//把i传递进去 对i加
AddTwo(i);
cout << "After AddTwo():" << i << endl;
return 0;
}
引用形参
#include<iostream>
#include<string>
using namespace std;
int doOp(int x, int y,int &减法结果,int &乘法结果,int &除法结果)//int &减法结果
{
int 加法结果;
加法结果 = x + y;
减法结果 = x - y;
乘法结果 = x * y;
除法结果 = x / y;
return 加法结果;
}
//不需要复制
//引用形参 不是为了修改实参
bool isshort(const string &s1, const string &s2)
{
return s1.size() < s2.size();
}
string::size_type find_char(const string &s, char c)
{
string::size_type i = 0;
while (i !=s.size() && s[i] != c)
++i;
return i;
}
int main()
{
int 结果 = find_char("hello world", 'o');//后面o不是字符"o"
cout << "在位置" << 结果 << "找到o" << endl;
int a = 10, b = 2;
int 加法结果,减法结果,乘法结果,除法结果;
加法结果=doOp(a, b,减法结果,乘法结果,除法结果);
cout << 加法结果<<","<<减法结果 <<","<<乘法结果<<","<<除法结果<< endl;
string s1("one");
string s2("hello");
// 把s1,s2 复制 传进去
if (isshort(s1,s2))
cout << "s1短";
else
cout << "s2短";
return 0;
}
引用形参交换指针
#include<iostream>
using namespace std;
//不是交换两个数
void ptrswap(int*&v1, int*& v2)
{
int *tmp=v2;//只有int这里加*
v2 = v1;
v1 = tmp;
}
int main()
{
int i = 10;
int j = 20;
int *pi = &i;//*pi前面加int
int* pj = &j;//交换前 :*pj指向j
cout << i << "," << j << endl;
ptrswap(pi, pj);//交换两个指针 直接写pi,pj 不是&*pj
cout << i << "," << j << endl;
cout <<"交换前指针"<< *pi << "," << *pj << endl;
ptrswap(pi, pj);
cout << "交换后指针"<<*pi << "," << *pj << endl;
return 0;
}
容器类型的vector 迭代器形参
#include<iostream>
#include<vector>
using namespace std;
// 非引用形参
//void print(vector<double> v)
//{
// vector<double>::iterator begin = v.begin();
// while (begin != v.end())
// {
// cout << *begin << endl;
// begin++;
// }//while循环的花括号不能少 少了就一直在循环
//
//}
// 引用形参
//void print_2(vector<double>& v)
//{
// vector<double>::iterator begin=v.begin();
// while (begin != v.end())
// {
// cout << *begin << endl;
// begin++;
// }
//
//}
//vector 容器的迭代器(最常用的做法)
void print_3(vector<double>::const_iterator beg,
vector<double>::const_iterator end)//注意(,)不加分号
{
//while(beg!=end)
//cout << *beg++ << endl;//这里不加{}
//或者下面这种
while(beg != end)
{
cout << *beg++;
if (beg != end)
cout << " ";
}
cout << endl;
}
double vectorSum(vector<double>::iterator begin,
vector<double>::iterator end)
{//这里要加{}包含while
double sum = 0.0;//放在while外面
while (begin != end)
{
sum += *begin++;
}
return sum;
}
int main()
{
vector<double> dvec;
//dvec.push_back(1, 1);错了(1,1)
/*dvec.push_back(1.1);
dvec.push_back(2.2);
dvec.push_back(3.3);*/
cout << "Enter double type elements for vector:(Ctrl+Z to end)" << endl;
double dval;
while (cin >> dval)
dvec.push_back(dval);
//把dvec复制到形参v
//不用复制
//print_2(dvec);
print_3(dvec.begin(), dvec.end());//这里是begin() 和end()
cout << "你输入的数是" << endl;//一定要用ctrl +z结束输入
//返回的也是迭代器
cout << "向量中数据元素之和是" << vectorSum(dvec.begin(), dvec.end());
return 0;
}
数组形参
#include<iostream>
using namespace std;
//不修改则加const 否则不加const
// x指向数组的第一个元素
void printValues(const int* x,const size_t size)//最好的写法
{
for (size_t i = 0;i != size;++i)
cout << x[i] << " ";//" "使得输出结果横者排列
cout << endl;
}
// 和 int *x 一样
// 传int类型数组
void printValues_2(const int x[],const size_t size)
//size_t size得加上 否则for循环里的size报错
{
for (size_t i = 0;i != size;++i)
cout << x[i] << " ";
cout << endl;
// 和int *x
// int x[]一样
}void printValues_3(const int x[10],const size_t size)
{
for (size_t i = 0;i != size; ++i)//(;;)
cout << x[i] << " ";
cout << endl;
}
//引用的方式
void printValues_4(int(&x)[10])//只有一个参数 不要size
{
for (size_t i = 0;i != 10;++i)//直接用[]中数字代入size位置
{
cout << x[i] << " ";
}
cout << endl;//写在循环外边
}
// x是一个指针,指向很多行的数组的第一行;
//每一行是10个数,一共有rowSize行
void printValues_5(int(*x)[10], int rowSize)
{
for (int i = 0;i != rowSize;++i)
{
for (int j = 0;j != 10;++j)
{
cout << x[i][j] << " ";
}
cout << endl;
}
}
//两个指针
void printValues_6(const int* beg, const int* end)
{
while (beg != end)
{
cout << *beg++ << " ";
}
cout << endl;
}
// 传字符数组(C风格字符串),最后一个字符是null
// x是指针,指向第一个字符
void printChars(const char* x)
{
while (*x != NULL)//while (*x)这两个写法一样
cout << *x++;
cout << endl;
}
int main()
{
char s[] = "Hello C++";
printChars(s);
return 0;//提前结束改cpp程序
int arr[] = { 2,4,6,8,0,1,3,5,7,9 };
int arr1[] = { 2,4,6,8,0,1,3,5};
printValues(arr, 10);
printValues_2(arr, 10);
printValues_3(arr, 10);
printValues_4(arr);
printValues_6(arr1, arr1+8);
int m[][10] = {
{1,2,3,4,5,6,7,8,9,0},
{2,4,6,8,0,1,3,5,7,9},
{0,9,8,7,6,5,4,3,2,1}
};//;的加
cout << "显示二维数组" << endl;
printValues_5(m, 3);
return 0;
}
递归
#include<iostream>
using namespace std;
void doA()
{
cout << "Hello" << endl;
doA();//循环
}
void 老奶奶讲故事()
{
cout << "从前有座山,山里有座庙,庙里有个老和尚,老和尚在给小和尚讲故事:" << endl;
老奶奶讲故事();
}
//n!=n*(n-1)!;递归
long 阶乘(int n)
{
if (n == 0)
return 1;
else
return n * 阶乘(n - 1);
}
//迭代 普通的循环 不是递归
long 阶乘2(int n)
{
long 结果 = 1;
for (int i = n;i > 0;i--)//i--不是--i i>0不是n>0
结果 = 结果 * i;//不是乘以n-1
return 结果;
}
int main()
{
//doA();
//老奶奶讲故事();
//cout<<阶乘(4)<<endl;
for (int num = 0;num < 10;++num)
{
cout << "递归:"<<num << "!" << 阶乘(num) << endl;
cout << "迭代:"<<num << "!" << 阶乘2(num) << endl;
}
cout << 阶乘2(4) << endl;
return 0;
}
函数原型和调用
//protos.cpp-using prototypes and function calls函数原型和函数调用
#include<iostream>
void cheers(int);//prototype :no return value
double cube(double x);//prototype:returns a double
void cheers(int n)
{
using namespace std;
for (int i = 0;i < n;i++)
cout << "cheers!";
cout << endl;
}
double cube(double x)
{
return x * x * x;
}
int main()
{
using namespace std;
cheers(5);//function call
cout << "Give me a number";
double side;
cin >> side;
double volume = cube(side);//function call
cout << "A" << side << "-foot cube has a volume of";
cout << volume << "cubic feet.\n";
cheers(cube(2));//prototype protection at work
//cin.get();
//cin.get();
return 0;
}
两个参数的函数
//twoarg.cpp--a function with 2 arguments
#include<iostream>
using namespace std;
void n_chars(char, int);
int main()
{
int times;
char ch;
cout << "Enter a character:";
cin >> ch;
while (ch != 'q')//q to quit
{
cout << "Enter an integer:";
cin >> times;
n_chars(ch, times);//function with two arguments
cout << "\nEnter another character or press the "
"q-key to quit:";
cin >> ch;
}
cout << "The value of times is" << times << ".\n";
cout << "Bye\n";
//cin.get();
//cin.get();
return 0;
}
void n_chars(char c, int n)//displays c n times
{
while (n-- > 0)//continue until n reaches 0
cout << c;
}
cmd不是内部文件报错处理
probability()函数
//lotto.cpp--probability of winning
#include<iostream>
//Note:some implementations require double instead of long double
long double probability(unsigned numbers, unsigned picks);
int main()
{
using namespace std;
double total, choices;
cout << "Enter the total number of choices on the game card and\n"
"the number of picks allowed:\n";
while ((cin >> total >> choices) && choices <= total)
{
cout << "You have one chance in";
cout << probability(total, choices);//compute the odds
cout << "of winning .\n";
cout << "Next two numbers (q to quit):";
}
cout << "bye\n";
//cin.get();
//cin.get();
return 0;
}
///the following function calculates the probability of picking picks
//numbers correctly from numbers choices
long double probability(unsigned numbers, unsigned picks)
{
long double result = 1.0;//here come some local variables
long double n;
unsigned p;
for (n = numbers, p = picks;p > 0;n--, p--)
result = result * n / p;
return result;
}
函数与数组
//arrfun1.cpp--functions with an array argument
#include<iostream>
const int ArSize = 8;
int sum_arr(int arr[], int n);//prototype
int main()
{
using namespace std;
int cookies[ArSize] = { 1,2,4,8,16,32,64,128 };
//some systems require require preceding int with static to
//enable array initialization
int sum = sum_arr(cookies, ArSize);
cout << "Total cookies eaten:" << sum << "\n";
//cin.get();
return 0;
}
//return the sum of an interger array
int sum_arr(int arr[], int n)
{
int total = 0;
for (int i = 0;i < n;i++)
total = total + arr[i];
return total;
}
将数组作为参数
//arrfun2.cpp--functions with an array argument
#include<iostream>
//using namespace std;
const int ArSize = 8;
int sum_arr(int arr[], int n);//无法解析??
//use std::instead of using directive
int main()
{
int cookies[ArSize] = { 1,2,4,8,16,32,64,128 };
//some systems require preceding int with static to
//enable array initialization
std::cout << cookies << "=array address,";
//some systems require a type cast:unsigned (cookies)
std::cout << sizeof cookies << "=sizeof cookies\n";
int sum = sum_arr(cookies, ArSize);
std::cout << "Total cookies eaten:" << sum << std::endl;
sum = sum_arr(cookies, 3);//a lie
std::cout << "First three eaters ate" << sum << "cookies.\n";
sum = sum_arr(cookies+4, 4);//a lie
std::cout << "Last four eaters ate" << sum << "cookies.\n";
//cin.geta();
return 0;
}
函数指针
//fun_prt.cpp -- pointers to functions
#include<iostream>
double besty(int);
double pam(int);
//second argument is pointer to a type double function that
//takes a type int argument
void estimate(int lines, double(*pf)(int));
int main()
{
using namespace std;
int code;
cout << "How many lines of code do you need?";
cin >> code;
cout << "Here's Betsy's estimate :\n";
estimate(code, besty);
cout << "Here's Pam's estimate:\n";
estimate(code, pam);
//cin.get();
//cin.get();
return 0;
}
double besty(int lns)
{
return 0.05 * lns;
}
double pam(int lns)
{
return 0.03 * lns + 0.0004 * lns * lns;
}
void estimate(int lines, double(*pf)(int))
{
using namespace std;
cout << lines << "lines will take";
cout << (*pf)(lines) << "hour(s)\n";
}
vs2019 右侧的解决方案资源管理器 界面找回
调试–>最后一个调试属性——>选定内容没有属性内容就正常(要是出现很多选项,就选择 常规)
函数指针示例
//fun_prt.cpp -- pointers to functions指向函数的指针
#include<iostream>
double besty(int);
double pam(int);
//second argument is pointer to a type double function that
//takes a type int argument
void estimate(int lines, double(*pf)(int));
int main()
{
using namespace std;
int code;
cout << "How many lines of code do you need?";
cin >> code;
cout << "Here's Betsy's estimate :\n";
estimate(code, besty);
cout << "Here's Pam's estimate:\n";
estimate(code, pam);
//cin.get();
//cin.get();
return 0;
}
double besty(int lns)
{
return 0.05 * lns;
}
double pam(int lns)
{
return 0.03 * lns + 0.0004 * lns * lns;
}
void estimate(int lines, double(*pf)(int))
{
using namespace std;
cout << lines << "lines will take";
cout << (*pf)(lines) << "hour(s)\n";
}
包含多个递归调用的递归
//ruler.cpp --using recursion to subdivide a ruler 递归划分
#include<iostream>
const int Len = 66;
const int Divs = 6;
void subdivide(char ar[], int low, int high, int level);
int main()
{
using namespace std;
char ruler[Len];
int i;
for (i = 1;i < Len - 2;i++)
ruler[i] = ' ';
ruler[Len - 1] = '\0';
int max = Len - 2;
int min = 0;
ruler[min] = ruler[max] = '|';
cout << ruler << endl;
for (i = 1;i <= Divs;i++)
{
subdivide(ruler, min, max, i);
cout << ruler << endl;
for (int j = 1;j < Len - 2;j++)
ruler[j] = ' ';//reset to blank ruler
}
return 0;
}
void subdivide(char ar[], int low, int high, int level)
{
if (level == 0)
return;
int mid = (high + low) / 2;
ar[mid] = '|';//不是"|"
subdivide(ar, low, mid, level - 1);
subdivide(ar, mid, high, level - 1);
}
包含一个递归调用的递归
//recur.cpp -- using recursion 使用递归
#include<iostream>
void countdown(int n);
int main()
{
countdown(4);//call the recursive function
//cin.get();
return 0;
}
void countdown(int n)
{
using namespace std;
cout << "Couting down..." << n << endl;
if (n > 0)
countdown(n - 1);//function calls itself
cout << n << ":Kaboom!\n";
}
函数和array 对象
//arrobj.cpp--functions with array objects带有数组对象的函数
#include<iostream>
#include<array>
#include<string>
using namespace std;
const int Seasons = 4;
const std::array<std::string, Seasons>Snames =
{ "Spring","Summer ","Fall","Winter" };
void fill(std::array <double, Seasons>* pa);
void show(std::array <double, Seasons>da);
int main()
{
array<double, 4>expenses;
fill(&expenses);
show(expenses);
//cin.get();
//cin.get();
return 0;
}
void fill(std::array<double, Seasons>* pa)
{
for (int i=0;i<Seasons;i++)
{
cout << "Enter " << Snames[i] << "expenses:";
cin >> (*pa)[i];
}
}
void show(array<double, Seasons>da)
{
double total = 0.0;
cout << "\nEXPENSES\n";
for (int i = 0;i < Seasons;i++)
{
cout << Snames[i] << ":$" << da[i] << '\n';
total += da[i];
}
cout << "Total:$" << total << '\n';
}
函数和string 对象
//topfive.cpp -- handling an array of string objects
#include<iostream>
#include<string>
using namespace std;
const int SIZE = 5;
void display(const string sa[], int n);
int main()
{
string list[SIZE];//an array holding 5 string object
cout << "Enter your" << SIZE << "favorite astronnomical sights:\n";
for (int i = 0;i < SIZE;i++)
{
cout << i + 1 << ":";
getline(cin, list[i]);//使用string 对象getline
}
cout << "Your list:\n";
display(list, SIZE);
//cin.get();
return 0;
}
void display(const string sa[], int n)
{
for (int i = 0;i < n;i++)
cout << i + 1 << ":" << sa[i] << endl;
}
传递结构地址
//strctptr.cpp--functions with pointer to structure arguments
#include<iostream>
#include<cmath>
//structure templates
struct polar
{
double distance;//distance from origin
double angle;//direction from origin
};
struct rect
{
double x;//horizontal distance from origin
double y;//vertical distance from origin
};
//prototypes
void rect_to_polar(const rect* pxy, polar* pda);
void show_polar(const polar* pda);
int main()
{
using namespace std;
rect rplace;
polar pplace;
cout << "Enter the x and y values:";
while (cin >> rplace.x >> rplace.y)//rplace.y 句点是成员运算符 区别于->
{
rect_to_polar(&rplace, &pplace);//pass addresses
show_polar(&pplace);//pass address
cout << "Next two numbers(q to quit):";
}
cout << "Done.\n";
return 0;
}
//show polar coordinates,converting angle to degrees
void show_polar(const polar* pda)
{
using namespace std;
const double Rad_to_deg = 57.29577951;
cout << "distance =" << pda->distance;//->间接成员运算符
cout << ",angle=" << pda->angle * Rad_to_deg;
cout << "degrees\n";
}
//convert rectangular to polar coordinates
void rect_to_polar(const rect* pxy, polar* pda)
{
using namespace std;
pda->distance =
sqrt(pxy->x * pxy->x + pxy->y * pxy->y);
pda->angle = atan2(pxy->y, pxy->x);
}
传递和返回结构
//travel.cpp-- using structures with functions
#include<iostream>
struct travel_time
{
int hours;
int mins;
};
const int Mins_per_hr = 60;
travel_time sum(travel_time t1, travel_time t2);
void show_time(travel_time t);
int main()
{
using namespace std;
travel_time day1 = { 5,45 };//5hrs,45 min
travel_time day2 = { 4,55 };//4hrs,55min
travel_time trip = sum(day1, day2);
cout << "Two-day total:";
show_time(trip);
travel_time day3 = { 4,32 };
cout << "Three-day total:";
show_time(sum(trip, day3));
//cin.get();
return 0;
}
travel_time sum(travel_time t1, travel_time t2)
{
travel_time total;
total.mins = (t1.mins + t2.mins) % Mins_per_hr;
total.hours = t1.hours + t2.hours +
(t1.mins + t2.mins) / Mins_per_hr;
return total;
}
void show_time(travel_time t)
{
using namespace std;
cout << t.hours << "hours,"
<< t.mins << "minutes\n";
}
返回C-风格字符串的函数
//strgback.cpp -- a function that returns a pointer to char
#include<iostream>
char* buildstr(char c, int n);//prototype
int main()
{
using namespace std;
int times;
char ch;
cout << "Enter a character:";
cin >> ch;
cout << "Enter an integer:";
cin >> times;
char* ps = buildstr(ch, times);
cout << ps << endl;
delete[] ps;//free memory
ps = buildstr('+', 20); //reuse pointer
cout << ps << "-DONE-" << ps << endl;
delete[] ps; //free memory
//cin.get();
//cin.get();
return 0;
}
//builds string made of n c characters
char* buildstr(char c, int n)
{
char* pstr = new char[n + 1];
pstr[n] = '\0';//terminate string
while (n-- > 0)
pstr[n] = c;//fill rest of string
return pstr;
}
将C-风格字符串作为参数的函数
//strgfun.cpp --functions with a string argument
#include<iostream>
unsigned int c_in_str(const char* str, char ch);
int main()
{
using namespace std;
char mmm[15] = "minimum";//string in an array
//some systems require preceding char with static to
//enable array inintialization
//char *wail = "ululate";//wail points to string 这样写报错了
unsigned int ms = c_in_str(mmm, 'm');
// unsigned int us = c_in_str(wail, 'u');
cout << ms << "m characters in " << mmm << endl;
//cout << us << "u characters in" << wail << endl;
//cin.get();
return 0;
}
//this function counts the number of ch characters
//in the string str
unsigned int c_in_str(const char * str, char ch)
{
unsigned int count = 0;
while (*str)//quit when *str is '\0'
{
if (*str == ch)
count++;
str++;//move pointer to next char
}
return count;
}