c++ - 对象组合 C++ : no matching function for call

标签 c++ class composition

我正在尝试创建一个名为luminary 的对象。该对象由thermometer对象、memory对象、Led对象组成。最后三个类(class)完全分开工作。但是,当我尝试将 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 必须是默认可构造的,这意味着它们应该具有默认构造函数,但是它们没有。

你可以使用 member initializer list这里:

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

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

关于c++ - 对象组合 C++ : no matching function for call,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31508370/

相关文章:

c++ - 当可变参数模板类继承自模板参数时,在调用基类型的方法时扩展参数包

java - 如何在 ArrayList 中存储然后访问类对象?

python - 为什么这段 Python 代码会出现名称错误?

python - 你能在 python 中循环创建类吗?

java - Java 代码中的聚合和组合

haskell - 将 compose 应用于 fmap

C++20 指定初始化器 char[]

C++ 2D 数组分配内存以避免段错误

Kotlin:将复合类属性公开为公共(public)主机类属性

c++ - QML 计时器未触发