错误:表达式必须具有类类型

时间:2014-09-24 03:10:21

标签: c++ class object

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

#include "Worker.h"

int main()
{

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

}

Worker.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
};

3 个答案:

答案 0 :(得分:3)

Most vexing parse

这一行:

Worker myWorker();

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

只需声明您的对象:

Worker myWorker;

答案 1 :(得分:0)

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

int main()
{

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

}

答案 2 :(得分:0)

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

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