//learanc11.cpp 函数的高级应用
#include<iostream>
#include<string>
using namespace std;
struct user {
int age;
};
/*
内联函数,需要在前面加上inline.
内联函数的优点就是效率高,省去了函数调用的步骤。缺点是如果函数被多个地方调用则比较占内存。
*/
inline int square(int n);
void swapv(int a, int b);
void swapr(int& a, int& b);//引用变量参数
void swapp(int* a,int* b);
void userr(user& u);//引用结构
string & stringr(string& s);
void defaultp(int a = 1, string b = "aaa");//默认参数
//函数重载,函数名相同,参数列表不同的函数叫做函数重载。
void hello(char* str,int n);
void hello(int n);
//函数模版
template <typename T> void swapt(T& a, T& b);
int main() {
//内联函数的调用和普通函数式一样的。
int n = square(10);
cout << n << endl;
//引用变量
int num = 100;//常规变量
int& numref = num;//引用变量,这里的&不是地址运算符。int&表示int类型的引用。必须在声明是进行初始化。相当于const指针 const int* pn = #
cout << "num=" << num << endl;
cout << "numref=" << numref << endl;
numref++;//num和numref的值和地址都相同,改变一个另一个也会跟着改变。
cout << "num=" << num << endl;
cout << "numref=" << numref << endl;
//将引用变量作为函数参数和指针作为参数的对比
int a = 111;
int b = 222;
cout << "a=" << a << " b=" << b << endl;
swapv(a, b);//不会交换变量的值
cout << "a=" << a << " b=" << b << endl;
swapr(a,b);//会交换变量的值
cout << "a=" << a << " b=" << b << endl;
swapp(&a, &b);//会交换变量的值
cout << "a=" << a << " b=" << b << endl;
//结构的引用变量
user u = { 10 };
userr(u);
cout << "age=" << u.age << endl;
//将类对象传递给参数的使用,c++的通常做法是使用引用。
string str = "hello";
string& str1 = stringr(str);
cout << str1 << endl;
/*
函数传递的时候,应该按值传递,还是引用传递,还是指针传递呢?
第一种情况不对数据进行修改:
1:如果数据对象很小,如内置类型或小型结构,则按值传递。
2:如果数据对象是数组,则使用const指针。
3:如果数据对象是较大的结构,使用const指针或者const引用。这样可以提高程序的效率,节省复制结构所需要的时间和空间。
4:如果数据对象是类对象,使用const引用。传递类对象参数的标准方式是按引用传递。
第二种情况对数据进行修改:
1:如果数据对象是内置类型,使用指针。
2:如果数据对象是数据,使用指针。
3:如果数据对象是结构,使用引用或指针。
4:如果数据对象是类对象,使用引用。
*/
//默认参数
defaultp();
defaultp(5);
defaultp(10,"bbbb");
//函数重载
char str2[] = "hello world";
hello(str2,11);
hello(10);
//函数模版
int aa = 100;
int bb = 200;
swapt(aa, bb);
cout << "aa=" << aa <<" bb=" << bb << endl;
string s1 = "aaaa";
string s2 = "bbbb";
swapt(s1, s2);
cout << "s1=" << s1 <<" s2=" << s2 << endl;
return 0;
}
inline int square(int n) {
return n * n;
}
void swapv(int a, int b) {
int temp = a;
a = b;
b = temp;
}
void swapr(int& a,int& b) {
int temp = a;
a = b;
b = temp;
}
void swapp(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
void userr(user& u) {
u.age = 100;
}
string& stringr(string& s) {
cout << s << endl;
s = "hello world";
return s;
}
void defaultp(int a, string b) {
cout << "a=" << a << " b=" << b << endl;
}
void hello(char* str,int n) {
cout << "hello(char* str,int n) " ;
char* pc = str;
char* pcend = str + n;
for (pc = str;pc != pcend;pc++) {
cout << *pc;
}
cout << endl;
}
void hello(int n) {
cout << "hello(int n) " << n << endl;
}
template <typename T> void swapt(T& a, T& b) {
T temp = a;
a = b;
b = temp;
}
输出结果:
100
num=100
numref=100
num=101
numref=101
a=111 b=222
a=111 b=222
a=222 b=111
a=111 b=222
age=100
hello
hello world
a=1 b=aaa
a=5 b=aaa
a=10 b=bbbb
hello(char* str,int n) hello world
hello(int n) 10
aa=200 bb=100
s1=bbbb s2=aaaa