[英]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.