我正在尝试学习指针,但我得到了这个错误。我是否需要更改头文件类Request?为什么我会收到这样的错误?
cannot convert `req' from type `Request' to type `Request *'
错误发生在这些行中:
//Store necessary information in a Request object for each request.
Request req(url, request, 1);
Request *reqq = req; //req points to the object
list->Append(reqq);
代码:
void
ClientThread(int request)
{
const int sz = 50;
char url[sz];
FILE *fp = fopen("url.txt", "r");
if (!fp)
printf(" Cannot open file url.txt!\n");
else {
int pos = 0;
char c = getc(fp);
while (c != EOF || pos == sz - 1) {
if (c == '\n') {
url[pos] = '\0';
serve(url);
pos = 0;
//Store necessary information in a Request object for each request.
Request req(url, request, 1);
Request *reqq = req; //req points to the object
list->Append(reqq);
}
else {
url[pos++] = c;
}
c = getc(fp);
}
fclose(fp);
}
}
我的request.h文件包含以下内容:
class Request
{
public:
//constructor intializes request type
Request(char *u, int rqtID, int rqtrID);
char *url;
int requestID;
int requesterID;
}
答案 0 :(得分:3)
您需要使用此处的address-of operator:
Request *reqq = &req; //req points to the object
// -------------^
请注意,在这种情况下&
{{1}}。
如果操作数是某种类型T的左值表达式,则运算符& 创建并返回类型为T *的prvalue。
答案 1 :(得分:1)
使用req
添加&req
的引用。指针类型接受指针值,而不是对象。
Request *reqq = &req; //req points to the object