为什么编译器看不到指定的默认参数值
Why is the compiler not seeing the default parameter value specified?
观察以下接口/实现:
properties.h
class Property
{
public:
Property(PropertyCollection * propertyCollection, std::string key,
std::string value, uint32_t identifier);
properties.cpp
Property::Property(PropertyCollection * propertyCollection,
std::string key, std::string value, uint32_t identifier = 0)
: propertyCollection(propertyCollection), key(key), value(value),
identifier(identifier) {}
可以看到,最后一个参数有一个默认初始化式。
但是,我仍然得到这个Eclipse错误:main.cpp
Properties properties (*file);
Property property (&properties, std::string("Cats"), std::string("Rule"));
没有匹配的函数来调用' Property::Property(Properties*, std::string, std::string) '
编辑:Properties
继承自PropertyCollection
。PropertyCollection
是一个纯虚拟类。
+----------------------+
| <<pure virtual>> |
| PropertyCollection |
+----------------------+
| |
+----------------------+
^
|
+
+-----------------------+
| Properties |
|-----------------------|
| |
+-----------------------+
在Java中,我将Properties
*视为* PropertyCollection
,并按原样传递引用。然而,在c++中,我必须以某种方式转换指针到基类吗?编辑:我猜不是。唯一的问题是默认初始化项的位置。
原因
看起来好像你从你的主源代码中包括properties.h
,然后链接到properties.cpp
内部,这在微不足道的情况下是完全没问题的。
但是当你做你正在做的事情时,编译器没有办法知道(在编译main的时候)你试图调用的构造函数有一个默认参数(这是不知道的,直到你链接到properties.cpp
)。
在main中,编译器只知道你告诉它的内容,更具体地说,它只知道
Property::Property (PropertyCollection * propertyCollection, std::string key,
std::string value, uint32_t identifier);
解决方案
简单且推荐的解决方案是将默认值规范移到
properties.h
中的构造函数声明中,这样编译器将拥有使事情按您希望的方式工作所需的所有信息。您需要将默认参数放在成员函数声明中,即在头文件中,而不是在其定义:
class Property
{
public:
Property(PropertyCollection * propertyCollection, std::string key,
std::string value, uint32_t identifier = 0);
在您展示的代码中,main
只能看到Property::Property(PropertyCollection*, std::string, std::string, uint32_t)
。
解决方案已经由juanchopanza提供了答案。我将介绍。h文件和。cpp文件在修改后的样子。
properties.h
class Property
{
public:
Property(PropertyCollection * propertyCollection, std::string key,
std::string value, uint32_t identifier = 0);
properties.cpp
Property::Property(PropertyCollection * propertyCollection,
std::string key, std::string value, uint32_t identifier)
: propertyCollection(propertyCollection), key(key), value(value),
identifier(identifier) {}
构造函数中:
Property(PropertyCollection * propertyCollection, std::string key, std::string value);
你的构造函数:
Property(Property * propertyCollection, std::string key, std::string value);
传递PropertyCollection
对象的地址,或者创建一个新的构造函数
- 如何使用默认参数等选择模板专业化
- 当函数模板参数是具有默认参数的类模板时,函数模板参数的推导如何执行
- 何时提供默认参数作为模板参数
- 将const引用参数初始化为默认参数会导致悬空引用吗
- 如何修复带有 clang 的参数'args'缺少默认参数的问题?
- 函数不接受 X 参数,函数使用默认参数
- initializer_list具有默认参数的构造函数
- C++ 带有默认参数的结构,可选择在构造函数中更改
- 为什么C++构造函数在继承中需要默认参数?
- 必须非常量别名参数及其默认参数常量
- C++ 默认参数使用其他参数
- 组合函数参数包和默认参数
- 如何定义 Vector2f 的默认参数?[SFML]
- 有条件地将默认参数传递给函数(使用"?"运算符)
- 使用具有默认参数的函数模板进行 decltype 会使结果混乱(一个有趣的问题或 gcc 的错误)
- 如何设置默认参数以防用户不输入另一个参数
- 结构 c++ 中的默认参数
- 构造函数委托与默认参数
- 默认参数和函数指针作为函数参数C++
- 如何在继承层次结构中调用具有默认参数的构造函数?