Default parameters, function overloading, use of references (C++)

foreword

This article mainly explains the default parameters, function overloading, and the use of references.


提示:以下是本篇文章正文内容,下面案例可供参考

1. What are the default parameters ?

The default function is the lack of a specified value for the specified parameter at the time of declaration or definition .

 The code is as follows (example):

#include <iostream>
using namespace std;
void f()
{
	cout << "f()" << endl;

}
void f(int a)
{
	cout << "f(int a)" << endl;
}
int main()
{
	int a = 0;
	f();
	f(a);
	return 0;
}

The result is as follows: 

1. Classification of default parameters

1. All default parameters

#include <iostream>
using namespace std;
void f(int a=10,int b=20,int c=30)
{
	cout << a+b+c << endl;
}

int main()
{
	int x = 0;
	int y = 0;
	int z = 10;
	f();
	return 0;
}

The result is as follows:

2. Semi-default parameters

#include <iostream>
using namespace std;

void f(int x,int y=10,int z=10)
{
	cout << x+y+z << endl;
}
int main()
{
	int x = 0;
	int y = 0;
	int z = 10;
	f(x);
	return 0;
}

The result is as follows:

 Notice:

  1. Semi-defaults must be given from right to left
  2. Default parameters cannot appear in both function declaration and definition
  3. Default value must be local or global

2. What is function overloading ?

The same function name can exist in the same scope at the same time, but the formal parameter lists of these same function names are different (such as: the number of parameters is different, the type is different, and the order of types is different ).

The code is as follows (example):

void f(int a, int b, int c)
{
	cout << a << endl;
	cout << b << endl;
	cout << c << endl;
}
void f(double a = 11.1, int b = 10, int c = 120)
{
	cout << a << endl;
	cout << b << endl;
	cout << c << endl;
}
int main()
{
	int x = 0;
	int y = 0;
	int z = 10;
	f(x,y,z);
	f();
	return 0;
}

result:

Notice: 

        1. Do not define ambiguous parameters

  1. void f(int a=10)
    {
    	cout << a << endl;
    }
    void f()
    {
    	cout << "hello world" << endl;
    }
    int main()
    {
    
    	f();
    	f();
    	return 0;
    }

 3. What is a reference ?

Reference is to give another name to a defined variable , but they share the same memory space .

Instructions:

Type & VariableName = Reference Entity; 

1. Citation properties 

  1. Must be initialized before reference
  2. A variable can have multiple references
  3. referenced name conflicts with defined name
int main()
{
	int x = 0;
	int& y = x;
	int& z = y;
	cout << x << endl;//0
	y = 10;
	cout << x << endl;//10
	z = 20;
	cout << x << endl;//20
	return 0;
}

result:

 


 

Summarize

This article mainly explains the default parameters, function overloading, and the use of references. It is very shallow and there is no in-depth explanation

Guess you like

Origin blog.csdn.net/qq_45591898/article/details/128819438