簡體   English   中英

C++,在另一個 object 構造函數中將 object 作為參數傳遞

[英]C++, Passing an object as a parameter in anothers object constructor

我在 3 個文件中有 3 個類。

  • 費查
  • 霍拉里奧.h
  • 記錄儀.h

我希望能夠創建一個新的 Recordatorio class ,其中包含 Fecha 和 Horario class 。

這是我主要的 function:

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 中遇到的錯誤如下:

錯誤:沒有匹配的 function 調用 '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;
}

霍拉里奧.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

霍拉里奧.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_;
}
Recordatorio::Recordatorio(Fecha fecha, Horario horario, string mensaje) :
    fecha_(fecha),
    horario_(horario),
    mensaje_(mensaje) {
}

這現在將為您的類使用默認的復制構造函數,而不是構造一個空的 object 然后分配它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM