我的代码:
#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/