error: expression must have a class type

后端 未结 3 1240
我寻月下人不归
我寻月下人不归 2020-12-04 00:50

I get the error: expression must have a class type Firstly, I don\'t understand why I am getting this error. I create and object and use it. in my main:

#in         


        
相关标签:
3条回答
  • 2020-12-04 01:37

    Assuming the implementation of the Worker class is ok and no other errors,

    int main()
    {
    
        Worker myWorker;
        myWorker.inputInfo();
        myWorker.displayPayBarGraph();
    
    }
    
    0 讨论(0)
  • 2020-12-04 01:38

    This error can also happen when the types are repeated in the call site of a constructor. Take this code for example:

    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
    }
    

    This mistake is surprisingly done by many beginners. The fix is to remove the types from the parameters, as you don't need to repeat the types of the variables when using them:

    Worker myWorker(a, b); // properly calls the constructor
    
    0 讨论(0)
  • 2020-12-04 01:42

    Most vexing parse :

    This line:

    Worker myWorker();
    

    declares a function taking no parameters and returning a Worker.

    Simply declare your object with :

    Worker myWorker;
    
    0 讨论(0)
提交回复
热议问题