C++ 将字符串指针传递到C++;(续)
这是这个问题的延续,一些好人已经帮了我: 我试图通过C++ 将字符串指针传递到C++;(续),c++,string,pointers,struct,C++,String,Pointers,Struct,这是这个问题的延续,一些好人已经帮了我: 我试图通过指针将各种字符串传递到结构的成员中,但我做了一些根本不正确的事情。我认为它不需要取消引用。下面的过程适用于其他类型的数据,如int或char。例如: typedef struct Course{ string location; string course; string title; string prof; string focus; int credit; int CRN;
指针
将各种字符串
传递到结构
的成员中,但我做了一些根本不正确的事情。我认为它不需要取消引用。下面的过程适用于其他类型的数据,如int
或char
。例如:
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;
. . .
}
我试图编译以下算法以初始化课程时出错:
void c_Init(Course *d, string *location, ... ){
c_SetLocation(d, &location);
. . .
}
错误:
错误:无法将'const char*'转换为'std::string*,或将参数'2'转换为'void c_Init
更改
void c_Init(课程*d,字符串*位置,…){
c_设置位置(d和位置);
}
}
到
void c_Init(课程*d,字符串位置,…){
c_设置位置(d,位置);
}
}
没有理由传递位置指针
*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);
. . .
}
我只是在你的建议(以及我最初认为正确的方法)不起作用时出于绝望才这么做的。我仍然很遗憾地收到同样的错误。因为你没有修改位置(我假设)将参数设置为string const&location我正在修改它。好吧,还有一个额外的函数可以这样做。但是不管你的建议如何,谢谢。