为什么编译器看不到指定的默认参数值

Why is the compiler not seeing the default parameter value specified?

本文关键字:默认 参数 编译器 看不到 为什么      更新时间:2023-10-16

观察以下接口/实现:

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继承自PropertyCollectionPropertyCollection是一个纯虚拟类。

 +----------------------+
 |    <<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对象的地址,或者创建一个新的构造函数