【问题标题】:Type error and pointer confusion类型错误和指针混淆
【发布时间】:2023-03-26 23:11:01
【问题描述】:

我正在尝试学习指针,但出现此错误。我需要更改头文件类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;

}

【问题讨论】:

  • reqRequestreqq 是指向 Request 的指针。没有从一种转换到另一种。
  • 地址运算符&用于将对象转换为指针:&req
  • @MarkRansom:& 运算符不会将对象转换为指针。它产生一个指针值,即对象的地址。
  • @KeithThompson,好吧,你用一些草率的语言抓住了我。对不起。

标签: c++ pointers typeerror


【解决方案1】:

您需要在这里使用address-of operator

Request *reqq = &req; //req points to the object 
// -------------^

注意&在这种情况下does not mean reference

如果操作数是某个类型 T 的左值表达式,则 operator& 创建并返回 T* 类型的纯右值。

【讨论】:

    【解决方案2】:

    使用&req 放置req 的引用。指针类型接受指针值,而不是对象。

    Request *reqq = &req; //req points to the object
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-12
      • 2011-08-15
      • 2010-09-25
      • 2011-09-04
      • 2016-11-08
      • 1970-01-01
      • 2012-10-15
      相关资源
      最近更新 更多