【问题标题】:Object Composition C++: no matching function for call对象组合 C++:没有匹配的调用函数
【发布时间】:2015-07-20 03:18:37
【问题描述】:

我正在尝试创建一个名为 luminary 的对象。该对象由温度计对象、内存对象、Led对象组成。最后三个课程完全分开。但是,当我尝试在 luminary 课程中将所有内容粘合在一起时,我收到了以下信息:

luminary.cpp:11:112: 错误:没有匹配函数调用‘Thermometer::Thermometer()’ luminary.cpp:11:112: 错误:没有匹配函数调用‘Memory::Memory()’
luminary.cpp:11:112: 错误:没有匹配函数调用‘Led::Led()’

luminary类头文件代码:

class Luminary{

public:
    //Constructor
    Luminary(Led led,Thermometer thermometer,Memory memory);

    //Atributes
    Led _led;
    Thermometer _thermometer;
    Memory _memory;
}

cpp 文件代码:

#include "luminary.h"
#include "Led.h"
#include "Thermometer.h"
#include "Memory.h"


//Constructor
Luminary::Luminary(Led led,Thermometer thermometer,Memory memory){

    _memory = memory;
    _thermometer = thermometer;
    _led = led;

}

为什么我会收到这些消息?

【问题讨论】:

  • 您需要为LedThermometerMemory定义默认构造函数
  • @ForhadAhmed:不太可能。这是一个基本的“分配而不是初始化”错误,通过为类提供零意义的默认构造函数来解决这个问题并不是正确的解决方案。

标签: c++ class composition


【解决方案1】:

根据您的来源,LedThermometerMemory 必须是默认可构造的,这意味着它们应该具有默认构造函数,但它们没有。

你可以在这里使用member initializer list

Luminary::Luminary(Led led,Thermometer thermometer,Memory memory) 
    : _led(led), _thermometer(thermometer), _memory(memory) {}

Here 讨论了为什么在大多数情况下应该使用初始化列表而不是赋值。

【讨论】:

  • @GabrielVilella 我添加了一个参考以获得更多信息,希望它可以帮助你更多。
猜你喜欢
  • 1970-01-01
  • 2021-09-21
  • 2016-11-23
  • 2012-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-08
  • 1970-01-01
相关资源
最近更新 更多