【问题标题】:no matching function for call to ..constructor调用 ..constructor 没有匹配的函数
【发布时间】:2016-08-08 21:29:06
【问题描述】:

我正在尝试编译涉及继承的代码。

#include "MapEntityClass.h"

class RectangularEntityClass:public MapEntityClass
{
  public:
    void drawOnMap(MapClass *mapObj) const;

  protected:
};

父类是MapEntityClass,它没有默认构造函数,但有一个值构造函数。编译时出现以下错误:

RectangularEntityClass.h: In constructor ‘RectangularEntityClass::RectangularEntityClass()’:
RectangularEntityClass.h:12:7: error: no matching function for call to ‘MapEntityClass::MapEntityClass()’
   class RectangularEntityClass:public MapEntityClass
   ^
RectangularEntityClass.h:12:7: note: candidates are:
In file included from main.cpp:1:0:
MapEntityClass.h:32:5: note: MapEntityClass::MapEntityClass(const PixelLocationClass&, const ColorClass&)
     MapEntityClass(
     ^
MapEntityClass.h:32:5: note:   candidate expects 2 arguments, 0 provided

知道有什么问题吗?

【问题讨论】:

  • 由于类现在是这样,编译器创建了 RectangularEntityClass 的默认构造函数。在该实现中,它尝试调用其父类的默认构造函数(默认行为)。您可能想自己定义 RectangularEntityClass 的默认构造函数,以便使用适当的值调用 MapEntityClass 的值构造函数
  • 嗯,你是说rectangleEntityClass的默认构造函数?
  • 是的。为了指定 MapEntityClass 使用哪个构造函数

标签: c++ inheritance


【解决方案1】:

在继承中,只有当父类没有构造函数或只有默认构造函数时,子类才需要有构造函数。

在任何情况下,如果父类碰巧有一个参数化的构造函数,子类应该有一个参数化的构造函数,它应该调用父类的构造函数。

例子:

class A {
    int aVal;
    public:
        A(int);
};

A::A(int aVal)
{
    this->aVal = aVal;
}

class B : public A {
    int bVal;
    public:
        B(int, int)
};

B::B(int aVal, int bVal) : A(aVal)
{
    this->bVal = bVal;
}

【讨论】:

  • 在你的最后一个函数中,你能不能把它写成: B::B(int aVal, int bVal) { A(aVal);这->bVal = bVal; }
  • 啊,我明白了,所以当你把它放在正文中时,它实际上是在尝试创建该类的实例对象?
  • 是的。就是这样:)
猜你喜欢
  • 1970-01-01
  • 2017-10-16
  • 1970-01-01
  • 2021-09-21
  • 2016-11-23
  • 2014-03-12
  • 2015-03-17
  • 2018-08-04
  • 2012-05-27
相关资源
最近更新 更多