簡體   English   中英

將字符串參數傳遞給另一個字符串

[英]Passing a string argument to another string

我定義了此類:

class Forum{
std::string title;
Thread* threads[5];

在Forum :: Forum的構造函數中,我想傳遞一個字符串參數來定義title(類型為string)

Forum::Forum(string *k) {
int i;
std::strcpy(&title.c_str(),k->c_str());

我在那兒有問題。在這段代碼中,我收到“一元'&'操作數所需的左值”錯誤。 如果我刪除'&',則會收到錯誤“從'const char *'到'char *'[-fpermissive]的無效轉換”。

有什么想法可以避免上述錯誤,我將如何使用strcpy(或其他方法)將參數傳遞給字符串類型?

除非打算省略標題,否則建議您傳遞const引用而不是指針:

 Forum::Forum(const string& k)

這使得必須提供名稱更加明確,並且還允許傳遞字符串文字作為名稱:

 Forum f("Main Forum");

然后,要復制std::string ,只需分配它或使用其復制構造函數即可。 strcpy僅適用於C樣式char*字符串。 在這種情況下,請使用成員初始化程序:

Forum::Forum(const string& k):
  title(k)
{
}

您不需要使用strcpy這將無法正常工作

使用字符串賦值運算符

Forum::Forum(string *k) {
    title = *k; 
}

還是更好

Forum::Forum(const string& k) {
    title = k; 
}

也許初始化列表

Forum::Forum(const string& k) : title(k) { }

后者是最好的

您絕對應該了解有關標准庫的更多信息。 在C ++中,您可以將一個std::string分配給另一個,而不會弄亂指針和strcpy

Forum::Forum(const std::string& k) {
    // int i; you aran't using this anywhere, so why declare it?
    // as pointed out by @EdHeal, this-> is not necessary here
    /*this->*/ title = k; 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM