Chapter 8 Exploring Functions

1. The nature of citations

int a = 1;
int& copy = a;
//实际是:指针常量
int* const copy = &a; 

Once a reference is specified, it cannot be used as a reference to other variables

2. About const and reference

non-reference-no-return ||reference-no-return similar

//1.可行
void test(int a);
int a = 1;
test(a);

//2.可行
void test(const int a);
int a = 1;
test(a);

//3.可行
void test(const int a);
const int a = 1;
test(a);

//4.可行
void test(int a);
const int a = 1;
test(a);

quote-has return

//1.可行
int& test(int& a){
    return a;
}
int a = 1;
int& temp = test(a);

//2.可行
const int& test(int& a){
    return a;
}
int a = 1;
const int& temp = test(a);

//3.可行
const int& test(const int& a){
    return a;
}
int a = 1;
const int& temp = test(a);

//4.不可行
int& test(const int& a){
    return a;
}
int a = 1;
int& temp = test(a);

In addition, when the reference return value is passed to a non-reference, it is passed by value

 3. Default parameters

Default parameters, default values ​​must be added from right to left

4. Function overloading

1. If the incoming parameter does not exist in the overloaded version, an error occurs

2. The reference and the type itself cannot appear at the same time. Such as: void test1(int a); void test1(int&a);

3. It is an error to have the same entry parameters but different return values, and function overloading cannot occur.

5. Function templates

1. Both typename and class can be used for template declaration

2. Function templates can also be overloaded.

3. Explicitly materialize the template:

//模板函数
template<class T>
void swap(T& a,T& b){
    T temp = a;
    a = b;
    b = temp;
}

template<> void swap(int &a,int& b)
//对于非int类型调用 模板函数
//对于int数据调用 显示具体化函数

4. Display instantiation

When the template is overloaded, C++ needs to perform overload resolution;

Generally, a more specific function is selected first to call.

function entry parameters,

No const reference and const reference, prefer to choose the same type as yourself

Guess you like

Origin blog.csdn.net/qq_42813620/article/details/130608390