代码之家  ›  专栏  ›  技术社区  ›  Anthony McCormick

如何将std::string变量传递到函数中

  •  2
  • Anthony McCormick  · 技术社区  · 15 年前

    我有一个C++方法,它采用一个变量,方法签名就是这样的:

    DLL returnObject** getObject( const std::string folder = "" );
    

    我试着传递:

    const std::string myString = "something";
    

    No matching function call to ... getObject( std::string&);
    

    我有几个问题。

    1. 如何传入没有“&”的普通std::字符串
    2. 这看起来像是可选的“folder=''”是吗?如果是这样,如何传递可选参数?
    2 回复  |  直到 13 年前
        1
  •  4
  •   Michael Burr    15 年前

    这个小例子的效果和预期的一样:

    #include <stdio.h>
    #include <string>
    
    class foo {
    public:
        void getObject( const std::string folder = "" );
    };
    
    int main ()
    {
        const std::string myString = "something";
    
        foo* pFoo = new foo;
    
        pFoo->getObject( myString);
        pFoo->getObject();    // call using default parameter
    
        return 0;
    }
    
    
    void foo::getObject( const std::string folder)
    {
        printf( "folder is: \"%s\"\n", folder.c_str());
    }
    

        2
  •  1
  •   Alexander Rafferty    15 年前

    这对我来说很好,把它和你正在做的比较一下:

    #include <string>
    
    void myFunc(const std::string _str)
    {
    }
    
    int main()
    {
        const std::string str = "hello world";
        myFunc(str);
        return 0;
    }