C++ Pass A String

后端 未结 8 1981
自闭症患者
自闭症患者 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条回答
  •  一生所求
    2020-12-23 11:54

    You should be able to call print("yo!") since there is a constructor for std::string which takes a const char*. These single argument constructors define implicit conversions from their aguments to their class type (unless the constructor is declared explicit which is not the case for std::string). Have you actually tried to compile this code?

    void print(std::string input)
    {
        cout << input << endl;
    } 
    int main()
    {
        print("yo");
    }

    It compiles fine for me in GCC. However, if you declared print like this void print(std::string& input) then it would fail to compile since you can't bind a non-const reference to a temporary (the string would be a temporary constructed from "yo")

提交回复
热议问题