簡體   English   中英

將字符串指針傳遞給C ++中的結構(續)

[英]Passing a string pointer to a struct in C++ (cont)

這是該問題的延續,一些好人已經幫助了我: 將字符串指針傳遞給C ++中的結構

我試圖通過pointer將各種string傳遞給Struct成員,但是我所做的事情根本上是不正確的。 我認為它不需要取消引用。 以下過程適用於其他類型的數據,例如intchar 例如:

typedef struct Course{
    string location;
    string course;
    string title;
    string prof;
    string focus;
    int credit;
    int CRN;
    int section;
}Course;


void c_SetLocation(Course *d, string location){
    d->location = location;
    . . .
}

嘗試編譯以下算法來初始化Course時出現錯誤:

    void c_Init(Course *d, string *location, ... ){
        c_SetLocation(d, &location);
        . . .

    }

錯誤:

error: cannot convert 'const char*' to 'std::string* or argument '2' to 'void c_Init

更改

void c_Init(Course * d,string * location,...){c_SetLocation(d,&location);

}

void c_Init(Course * d,字符串位置,...){c_SetLocation(d,location);

}

沒有理由傳遞位置指針。

*location; //this is de-referencing
&location; //this is address of a variable (pointer to a variable)

因此,為了將字符串傳遞到c_SetLocation中,您應該取消引用它:

 void c_Init(Course *d, string *location, ... ){
    c_SetLocation(d, *location);
    . . .
}

暫無
暫無

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

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