current position:Home>Embedded Linux foundation: c++ (IV) overloaded pointer reference

Embedded Linux foundation: c++ (IV) overloaded pointer reference

2022-06-24 09:10:23da..

1. heavy load The pointer quote

 Insert picture description here

1.1 heavy load

Function names are the same , But the parameters are different , Call a function with the same function name .

#include <iostream>

using namespace std;

int add(int a, int b)
{
    
	cout<<"add int+int"<<endl;
	return a+b;
}

int add(int a, int b, int c)
{
    
	cout<<"add int+int+int"<<endl;
	return a+b+c;
}

double add(double a, double b)
{
    
	cout<<"add double+double"<<endl;
	return a+b;
}

double add(int a, double b)
{
    
	cout<<"add int+double"<<endl;
	return (double)a+b;
}

double add(double b, int a)
{
    
	cout<<"add double+int"<<endl;
	return (double)a+b;
}



int main(int argc, char **argv)
{
    
	add(1, 2);
	add(1, 2, 3);
	add(1.0, 2.0);
	add(1, 2.0);
	add(1.0, 2);

	return 0;
} 

When I perform

add(1, 2);
add(1, 2, 3);
add(1.0, 2.0);
add(1, 2.0);
add(1.0, 2);

When , The parameter passed in is int,int, So my compiler chooses the first function , Or the second function . Therefore, you can only overload functions through different parameters , Functions cannot be overloaded by different return values of functions

1.2 Pointer and reference

#include <iostream>

using namespace std;

int add_one(int a)
{
    
	a = a+1;
	return a;
}

int add_one(int *a)// The pointer 
{
    
	*a = *a + 1;
	return *a;
}

int add_one_ref(int &b)// quote 
{
    
	b = b+1;
	return b;
}

int main(int argc, char **argv)
{
    
	int a = 99;
        int &c = a;
	cout<<add_one(a)<<endl;
	cout<<"a = "<<a<<endl;

	cout<<add_one(&a)<<endl;
	cout<<"a = "<<a<<endl;

	cout<<add_one_ref(a)<<endl;// Same as the first one , Why?  
	cout<<"a = "<<a<<endl;

        c++;
        
	cout<<"a = "<<a<<endl;
	cout<<"c = "<<c<<endl;

	return 0;
}

First picture , The difference between normal use of functions and call pointers .

 Insert picture description here

second , The third picture refers to the effect of quotation .b By a After quoting ,b It points to a.

 Insert picture description here
 Insert picture description here

Be careful : The reference is as follows ,

int &b=a;

The assignment is a variable , Cannot be constant .

int &b=1;// This is wrong 

copyright notice
author[da..],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/175/202206240746598396.html

Random recommended