No default constructor exists for class error

前端 未结 3 707
盖世英雄少女心
盖世英雄少女心 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:43

    The problem is here:

    Stuff(Thing thing) {
        this->thing = thing;
    }
    

    By the time you enter the constructor's body, the compiler will have already initialized your object's data members. But it can't initialize thing because it does not have a default constructor.

    The solution is to tell the compiler how to initialize it by using an initlizer list.

    Stuff(Thing thing) : thing(thing) {
        // Nothing left to do.
    }
    

    This is less typing, cleaner code and more efficient. (More efficient, because if the variable is going to be initialized anyway, then why initialize it with an unwanted value first just to assign another one as quickly as you can? Of course, since your current code doesn't even compile, “more efficient” is a somewhat dubious statement, here.)

    0 讨论(0)
  • 2021-01-13 17:50

    Initialize thing member in Stuff with initializer list:

    class Stuff {
    public:
        Thing thing;  // an instance of thing is declared here but it cannot construct it
        Stuff(Thing thing): thing(thing) { }
    };
    
    0 讨论(0)
  • 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){};
    
    0 讨论(0)
提交回复
热议问题