【发布时间】:2020-05-10 19:43:39
【问题描述】:
我在 3 个文件中有 3 个类。
- Fecha.h
- Horario.h
- Recordatorio.h
我希望能够创建一个新的 Recordatorio 类,其中包含 Fecha 和 Horario 类。
这是我在 main 中的功能:
Recordatorio recordatorio(Fecha(5, 10), Horario(9, 0), "Clase Algo2");
注意:Fecha(5,10) 和 Horario(9,10) 工作正常。
这是我的 Recordatorio.cpp 中的代码:
#include "Recordatorio.h"
#include "Fecha.h"
#include "Horario.h"
#include <iostream>
#include <string>
using namespace std;
Recordatorio::Recordatorio(Fecha fecha, Horario horario, string mensaje){
fecha_ = fecha;
horario_ = horario;
mensaje_ = mensaje;
}
void Recordatorio::mensaje(){
cout << mensaje_ << endl;
}
这在我的 Recordatorio.h 中:
#ifndef RECORDATORIO_H
#define RECORDATORIO_H
#include "Fecha.h"
#include "Horario.h"
#include <string>
class Recordatorio
{
public:
Recordatorio(Fecha fecha, Horario horario, std::string mensaje);
void mensaje();
private:
Fecha fecha_;
Horario horario_;
std::string mensaje_;
};
#endif // RECORDATORIO_H
我在 Recordatorio.cpp 中遇到的错误如下:
错误:没有匹配的函数调用 'Fecha::Fecha()'
编辑:Fecha.h
#ifndef FECHA_H
#define FECHA_H
using uint = unsigned int;
class Fecha{
public:
Fecha(uint mes,uint dia);
uint mes();
uint dia();
void incrementar_dia();
private:
uint mes_;
uint dia_;
};
#endif // FECHA_H
Fecha.cpp
#include "Fecha.h"
uint dias_en_mes(uint mes) {
uint dias[] = {
// ene, feb, mar, abr, may, jun
31, 28, 31, 30, 31, 30,
// jul, ago, sep, oct, nov, dic
31, 31, 30, 31, 30, 31
};
return dias[mes - 1];
}
uint Fecha::mes() {
return mes_;
}
uint Fecha::dia() {
return dia_;
}
Fecha::Fecha(uint dia, uint mes){
dia_ = dia;
mes_ = mes;
}
void Fecha::incrementar_dia(){
uint maximo_dia_mes = dias_en_mes(mes_);
if (dia_ < maximo_dia_mes){
dia_++;
} else {
dia_ = 1;
if (mes_ != 12){
mes_++;
} else {
mes_ = 1;
}
}
return;
}
Horario.h:
#ifndef HORARIO_H
#define HORARIO_H
using uint = unsigned int;
class Horario
{
public:
Horario(uint hora, uint min);
uint hora();
uint min();
private:
uint hora_;
uint min_;
};
#endif // HORARIO_H
Horario.cpp:
#include "Horario.h"
using uint = unsigned int;
Horario::Horario(uint hora, uint min){
hora_ = hora;
min_ = min;
}
uint Horario::hora() {
return hora_;
}
uint Horario::min() {
return min_;
}
【问题讨论】:
-
你能包含 Fecha 类的代码吗?从错误消息中,我认为它不是默认可构造的。
-
为你的构造函数使用一个初始化列表,那么它不需要是默认可构造的。
-
已编辑。 @PeteFordham,你能举个例子吗?
-
编辑并添加了两个类@Philipp Claßen
-
你有一个答案,我只是补充一点,以提高内存效率,将你的对象作为 const 引用传递,例如
Recordatorio(const Fecha & fecha, const Horario & horario, const string & mensaje)。这会保存一份副本。