No default constructor exists for class error

前端 未结 3 711
盖世英雄少女心
盖世英雄少女心 2021-01-13 16:55

Some simple code:

class Thing {
public:
    int num;
    Thing(int num) { 
        this->num = num; 
    }
};

class Stuff {
public:
    Thing thing;  //          


        
3条回答
  •  不知归路
    2021-01-13 17:53

    The only constructor for Thing takes an int parameter.

    Thus, when you declare:

    Thing thing;
    

    With no arguments, how does it know what num should be?

    As the error states, there is 1 expected, but none provided. You need to either add a default constructor:

    Thing::Thing(void) : num(0){};
    

    or alternatively modify the argument:

    Thing::Thing(int num=0)
    

    In both cases I have used 0, but this should be whatever you think num should be 'by default', when nothing is specified.

    Without this, Stuff's Thing must have a value to initialise it; this is supported via the initialisation list, which you neglected to use in your Thing::Thing (see above), and as a side-note your this->num is not necessary, num is sufficient.

    Stuff::Stuff(Thing inThing) : thing(inThing){};
    

提交回复
热议问题