[英]Passing a string pointer to a struct in C++
我試圖通過pointer
將各種string
傳遞給Struct
成員,但是我所做的事情根本上是不正確的。 我認為它不需要取消引用。 以下過程適用於其他類型的數據,例如int
或char
。 例如:
typedef struct Course {
string location[15];
string course[20];
string title[40];
string prof[40];
string focus[10];
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* {aka std::basic_string<char>*}' for argument '2' to 'void c_Init(Course*, std::string*, ..
例如,您實際上是在location
字段中定義一個由15個字符串組成的數組。 使用常規字符串; 例如:
typedef struct Course {
string location;
string course;
string title;
string prof;
string focus;
int credit;
int CRN;
int section;
} Course;
或使用char數組:
typedef struct Course {
char location[15];
char course[20];
char title[40];
char prof[40];
char focus[10];
int credit;
int CRN;
int section;
} Course;
聲明char a[10]
,將創建一個10個字符的數組。 聲明std::string
,您正在創建一個可以增長為任意大小的字符串。 聲明std::string[15]
,您正在創建一個由15個字符串組成的數組,該數組可以增長為任意大小。
這是您的結構應如下所示:
typedef struct Course {
std::string location;
std::string course;
std::string title;
std::string prof;
std::string focus;
int credit;
int CRN;
int section;
} Course;
string location[15]
表示您想創建一個string
15個實例,並且每個單獨的實例可以具有任意長度的文本。
代替d->location
,您需要分配這15個字符串之一: d->location[0] = location
, d->location[1] = location
等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.