C++ Pass A String

后端 未结 8 2014
自闭症患者
自闭症患者 2020-12-23 10:51

Quick probably obvious question.

If I have:

void print(string input)
{
  cout << input << endl;
}

How do I call it like

8条回答
  •  萌比男神i
    2020-12-23 11:42

    You can write your function to take a const std::string&:

    void print(const std::string& input)
    {
        cout << input << endl;
    }
    

    or a const char*:

    void print(const char* input)
    {
        cout << input << endl;
    }
    

    Both ways allow you to call it like this:

    print("Hello World!\n"); // A temporary is made
    std::string someString = //...
    print(someString); // No temporary is made
    

    The second version does require c_str() to be called for std::strings:

    print("Hello World!\n"); // No temporary is made
    std::string someString = //...
    print(someString.c_str()); // No temporary is made
    

提交回复
热议问题