不存在用于类错误的默认构造函数 [英] No default constructor exists for class error

查看:232
本文介绍了不存在用于类错误的默认构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一些简单的代码:

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

class Stuff {
public:
    Thing thing;  // an instance of thing is declared here but it cannot construct it
    Stuff(Thing thing) {
        this->thing = thing;
    }
};

int main() {
    Thing thing = Thing(5);
    Stuff stuff = Stuff(thing);
}

所以在这里,我正在尝试确定应该如何服用Stuff的构造函数中Thing的新实例,但没有指向它,因为我希望Stuff拥有自己的副本。当然,我不能像上面那样声明,因为它正在尝试对其进行初始化。

So here, I'm trying to work out how I should be taking a new instance of Thing in the constructor of Stuff without pointing to it as I want Stuff to hold its own copy. Of course, I can't declare thing like I have above because it's trying to initialise it.

如何解决将新对象副本分配给a的问题。

How can I get around this problem of assigning a new object copy to a class' variable through its constructor?

确切的错误是:

In constructor 'Stuff::Stuff(Thing)':
error: no matching function for call to 'Thing::Thing()'
  Stuff(Thing thing){ this->thing = thing; }

candidate expects 1 argument, 0 provided


推荐答案

问题在这里:

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.)

这篇关于不存在用于类错误的默认构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆