【问题标题】:Error : Type 'struct a` does not provide a call operator错误:类型“struct a”不提供调用运算符
【发布时间】:2019-10-18 07:49:39
【问题描述】:

我正在编写以下代码并创建结构CPuTimeState 的对象:

struct CpuTimeState
  {
    ///< Field for time spent in user mode
    int64_t CS_USER = {};
    ///< Field for time spent in user mode with low priority ("nice")
    int64_t CPU_TIME_STATES_NUM = 10;

    std::string cpu_label;

    auto sum() const {
      return CS_USER + CS_NICE + CS_SYSTEM + CS_IDLE + CS_IOWAIT + CS_IRQ + CS_SOFTIRQ + CS_STEAL;
    }
  } cpu_info_obj;  // struct CpuTimeState

我声明了一个结构对象的向量,例如:

std::vector<CpuTimeState> m_entries;

我想在这样的函数中调用它:

  {
    std::string line;
    const std::string cpu_string("cpu");
    const std::size_t cpu_string_len = cpu_string.size();
    while (std::getline(proc_stat_file, line)) {
      // cpu stats line found
      if (!line.compare(0, cpu_string_len, cpu_string)) {
        std::istringstream ss(line);

        // store entry
        m_entries.emplace_back(cpu_info_obj());
        cpu_info_obj &entry = m_entries.back();

        // read cpu label
        ss >> entry.cpu_label;

        // count the number of cpu cores
        if (entry.cpu_label.size() > cpu_string_len) {
          ++m_cpu_cores;
        }

        // read times
        //for (uint8_t i = 0U; i < CpuTimeState::CPU_TIME_STATES_NUM; ++i) {
          ss >> entry

        }
      }
    }

它在编译时抛出此错误:Type 'struct CpuTimeState 不提供调用运算符。

【问题讨论】:

    标签: c++


    【解决方案1】:

    上线

    m_entries.emplace_back(cpu_info_obj());
    

    cpu_info_obj 是一个变量,而不是一个类型。您正在尝试在未实现该运算符的变量上调用 operator()。这就是编译器所抱怨的。

    要构造结构的新实例,您需要调用结构的构造函数:

    m_entries.emplace_back(CpuTimeState());
    

    但是,通过传入一个参数,您是在告诉emplace_back() 调用该结构的复制构造函数。更好的选择是完全省略参数并让emplace_back() 为您调用结构的默认构造函数:

    m_entries.emplace_back();
    

    【讨论】:

      猜你喜欢
      • 2022-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-24
      • 1970-01-01
      • 2020-11-19
      • 1970-01-01
      • 2015-12-24
      相关资源
      最近更新 更多