2014-09-26 118 views
0

我需要将非常量C字符串读入C++字符串。但是,我只看到字符串类中的常量C字符串读入字符串类的方法。将非常量C字符串读入字符串类

有没有办法在C++中做到这一点?

更新:

#include <iostream> 

using namespace std; 

int main(int argc, char** argv) 
{ 
    string a; 

    // other code here 

    a(argv[0]); 

    cout << a << endl; 
    return 0; 
} 

错误:

test.cpp: In function 'int main(int, char**)': 
test.cpp:11:14: error: no match for call to '(std::string {aka std::basic_string<char>}) (char*&)' 
    a(argv[0]); 

我做了一些更多的调查,并替换argv的一个常量字符串[0],发现我仍然有一个类似的错误消息。现在更好的问题是:如何声明一个对象并稍后调用其构造函数?

+2

显示代码。到目前为止,你有什么代码? – 2014-09-26 06:03:45

+0

“Off topic”?你们是荒谬的。 – 2014-09-26 14:02:20

+0

我已添加代码。看起来像我对这个问题的原始诊断是不正确的。 – David 2014-09-26 18:54:55

回答

4

你误解了函数签名的含义。转换将其参数设置为const char *,但这并不意味着您无法将char*传递给它。它只是告诉你这个函数不会修改它的输入。你为什么不试试呢?

#include <iostream> 
#include <string> 

int main() 
{ 
    char str[] = "hello"; 
    std::string cppstr = str; 
    std::cout << cppstr << endl; 
    return 0; 
} 
+0

更具体地说,类型std :: string的* objects *不可调用,只有std :: string的构造函数可以被调用。 – o11c 2014-09-26 21:03:40