【问题标题】:error: expression must have a class type错误:表达式必须具有类类型
【发布时间】:2014-09-24 03:10:20
【问题描述】:

我得到错误:表达式必须有一个类类型 首先,我不明白为什么会收到此错误。我创建并反对并使用它。 在我的主要:

#include "Worker.h"

int main()
{

    Worker myWorker();
    myWorker.inputInfo();
    myWorker.displayPayBarGraph();

}

工人.h

//Worker.h
//Definition of class Workers
//Member functions are defined in Worker.cpp


//Worker class defintion 

class Worker
{
public:
    Worker();               //constructor initializes worker type

    void inputInfo();           //attains worker information
    void displayPayBarGraph();  //prints a bar graph representation of the pay

private:

    int workerCode;     //worker type
    //PAY FOR EACH WORKER
    double code1pay;            //manager
    double code2pay;            //hourly workers
    double code3pay;            //commission workrs
    double code4pay;            //pieceworkers

    int hourlyWorkerPay(double, int);   //returns the pay of hourly workers
    int commissionPay(int);     //returns the commission workers pay
    int pieceWorkerPay(int, int);   //returns the pieceworkers pay
};

【问题讨论】:

  • 在哪一行给出错误?

标签: c++ class object


【解决方案1】:

Most vexing parse

这一行:

Worker myWorker();

声明一个函数不带参数并返回Worker

只需声明您的对象:

Worker myWorker;

【讨论】:

    【解决方案2】:

    假设Worker类的实现没问题,没有其他错误,

    int main()
    {
    
        Worker myWorker;
        myWorker.inputInfo();
        myWorker.displayPayBarGraph();
    
    }
    

    【讨论】:

      【解决方案3】:

      当类型在构造函数的调用站点中重复时,也会发生此错误。以这段代码为例:

      class Worker {
      public:
          Worker(int a, int b);
          void inputInfo();
      };
      
      int main() {
          int a, b;
      
          // Notice how that this looks like a function declaration.
          // The types of a and b are repeated, but shouldn't.
          Worker myWorker(int a, int b);
      
          myWorker.inputInfo(); // error! expression must have a class type
      }
      

      这个错误出乎意料地被许多初学者所犯。解决方法是从参数中删除类型,因为在使用它们时不需要重复变量的类型:

      Worker myWorker(a, b); // properly calls the constructor
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-09-26
        • 2017-07-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-07
        相关资源
        最近更新 更多