2014-09-26 122 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