No default constructor exists for class error

前端 未结 3 730
盖世英雄少女心
盖世英雄少女心 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.)

提交回复
热议问题