简体   繁体   中英

Pass string class variable by reference in C++

Look at the following code:

#include <iostream>
#include <string>
using namespace std;
void reverseStr(string arr, int start, int end)
{
    while (start < end)
    {
        swap(arr[start], arr[end]);
        ++start;
        --end;
    }
}
int main()
{
    string str = "CPP";
    reverseStr(str, 0, 3);
    cout << str;
    return 0;
}

The output is CPP, while PCC is expected.

Question: How to pass string by reference in C++? Are strings a normal array? If yes then the reference must be passed automatically, while it just creates a copy in the formal parameters.

My question is that why I have to use my function like void reverseStr(string &arr, int start, int end) instead of just void reverseStr(string arr, int start, int end) . Why I have to use extra & informal parameters? Aren't string variables just other arrays?

How to pass string by reference in C++?

You simply add & to the parameter.

Are strings a normal array?

No, std::string is not an array.

Reference with & in function parameter, this means you pass a reference to the string you initialize in the main function. Without & you will just be passing a copy and the changes you make in the copy don't reflect in the original.

Also the call should be:

reverseStr(str, 0, 2);

Range 0 to 2, or better yet:

reverseStr(str, 0, str.size() - 1);

As you can see by the use of .size() method, an std::string is not a char array, it's a typedef of the class template std::basic_string<char> .

Learn more about what C++ string type is in https://pt.cppreference.com/w/cpp/string

The syntax for references in C++ is

void reverseStr(string &arr, int start, int end);

You can think about arr as a pointer, which is automatically dereferenced.

More information about references here .

You have to pass by reference because that's how the language is designed.

Your theory that "strings are arrays" is incorrect. Strings are strings.

It is true that, for historical reasons, passing C arrays by value actually appears to pass them by reference (in reality the array's name is decaying to a pointer). But that's not what you have here, and it's not how the rest of the language works.

If you pass by value, usually, you get a copy . So your function operates on a copy. Passing a reference means you operate on the original object, instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM