C + + summary function parameter, which returns a const object and a non-const object

Source: Internet
Author: User

Non-reference formal parameters
//交换函数,传递的实参只是参数的副本。并不能起到交换作用void swap(intint b) {    int m  = a;    a = b;    b = m;}
Pointer parameters
//可以起到交换作用void swap(int*aint*b) {    intm  *a;    *a*b;    *bm;}
Reference formal parameters
//可以起到交换作用void swap(intint &b) {    int temp = a;    a = b;    b = temp;}
Const formal Parameter

modifying parameters with const to avoid modification of arguments

string::size_type length(conststring &str) {    return str.size();}
Using arrays as formal parameters
//1void m(int a[]) {    cout << a[0] <<  endl;}//2void m(int *a) {    a[03;    cout << a[0] <<  endl;}int a[] = {123};m(a);

You can also use the const array parameter
General use of non-const formal parameters, the actual participants copied a copy of the delivery.
But for arrays, the array is silently converted to pointers, and parameter passing is a copy of the pointer, pointing to the first element of the array, changing the value, and changing the value of the array element.

Returns a non-const object

Copy a copy of the object you want to return back to

conststring getString(conststringconststring &str2) {    return str1.size() < str2.size()? str1 : str2;}
Returns the Cons object

No replication returns the original object directly, but never return a reference to the local object, because the function finishes running the objects to be destroyed

conststring &getString(conststringconststring &str2) {    return str1.size() < str2.size()? str1 : str2;}

C + + summary function parameter, which returns a const object and a non-const object

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.