Cpp不需要默认构造函数

问题描述 投票:0回答:2

我的代码:

#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。

提前感谢!

c++ constructor default
2个回答
2
投票
您可能希望重写构造函数以使用初始化列表列表。否则,将在您可以在构造函数主体中初始化成员之前使用默认的构造函数:

  • 从以上链接的文档中引用(重点为我:):>

    在构成构造函数功能体的复合语句开始执行之前,所有直接基,虚拟基和非静态数据成员的初始化已完成。

    成员初始化程序列表是可以指定这些对象的非默认初始化的位置。对于不能默认初始化的成员,例如引用成员和const限定类型的成员,必须指定成员初始值设定项。

    示例:

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

    使用成员初始化器列表:

    BaseProduct::BaseProduct( const ProductBaseType baseType, const int id, const int quantity, const Location location ) : // the colon marks the start of the member initializer list _baseType(baseType), _id(id), _quantity(quantity), _location(location) { // body of ctor can now be empty } }

    这使您可以使用无法默认构造的对象组成。

  • 1
    投票
    使用成员初始化器列表:
    © www.soinside.com 2019 - 2024. All rights reserved.