【问题标题】:invalid conversion from 'void*' to class(c++)从 'void*' 到 class(c++) 的无效转换
【发布时间】:2014-04-28 22:28:11
【问题描述】:

好的,这是我的代码:

StatusType System::AddJobSearcher(void *DS, int engineerID, int reqSalary) {
    if(DS == NULL || engineerID < 0 || reqSalary < 0) return INVALID_INPUT;
    System* system = DS;
    Engineer* engineer = new Engineer(engineerID, reqSalary);
    if(!engineer) return ALLOCATION_ERROR;
    if(system->All.isIn(*engineer->generateIdKey())) { 
        delete(engineer);
        return FAILURE;
    }
    system->All.insert(*engineer->generateIdKey(), *engineer); 
    return SUCCESS;
}

现在,system 是一个类,而 DS 应该是指向一个类的指针。 当我尝试将新创建的系统指向 DS(System* system = DS;) 我得到:

从 'void*' 到 'System*' 的无效转换 [-fpermissive]

我该如何解决这个问题

【问题讨论】:

  • 多么糟糕的代码。你确定你懂 C++?
  • 不是真的...但是谢谢:)

标签: c++ pointers type-conversion


【解决方案1】:

既然你知道DS 的类型是System*,你应该改变参数类型:

StatusType System::AddJobSearcher(System* DS, int engineerID, int reqSalary) {
//                                ^^^^^^

如果您碰巧将void* 作为第一个参数传递,您应该重构您的代码,这样您就不必这样做了。

【讨论】:

    【解决方案2】:

    在 C++(与 C 相反)中,您不能将 void * 类型的指针隐式转换为其他类型的指针。你必须明确地这样做

    System* system = static_cast<System*>( DS );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-30
      • 2013-08-19
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 2010-12-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多