c++ - Cpp 在不需要时询问默认构造函数

标签 c++ constructor default

我的代码:

#include "BaseProduct.h"

BaseProduct::BaseProduct(
    const ProductBaseType baseType,
    const int id,
    const int quantity,
    const Location location
    ) {
    _baseType = baseType;
    _id = id;
    _quantity = quantity;
    _location = location;
}

我得到的错误:

no default constructor exists for class "Location"

我知道 Location 没有任何默认构造函数,它的目的是...... 如果有任何相关性,我会使用 VSCode。

提前致谢!

最佳答案

您可能希望重写构造函数以使用初始化列表形式。否则,在您可以在构造函数主体中初始化它们之前,默认构造函数将用于您的成员:

引用上面链接的文档(强调我的):

Before the compound statement that forms the function body of the constructor begins executing, initialization of all direct bases, virtual bases, and non-static data members is finished. Member initializer list is the place where non-default initialization of these objects can be specified. For members that cannot be default-initialized, such as members of reference and const-qualified types, member initializers must be specified.

例子:

BaseProduct::BaseProduct(
    const ProductBaseType baseType,
    const int id,
    const int quantity,
    const Location location
    ) : _baseType(baseType), _id(id), _quantity(quantity), _location(location) { }

关于c++ - Cpp 在不需要时询问默认构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59137948/

相关文章:

c++ - makefile文件名参数

android - 更改 Android App 的默认字体

javascript - 我需要 jquery 中的脚本,使该页面成为浏览器中的默认主页网站

c++ - sqlite3程序收到信号SIGSEGV,sqlite3_get_table()中出现段错误

c++ - Xcode 中的奇怪日志

c++ - 在不声明成员变量的情况下更改按钮颜色

javascript - 创建包含或不包含 `new` 的数组

java - 类中的方法无法应用于给定类型错误

C++ 避免构造对象

Linux:在默认浏览器中打开 URL 的命令