1

Как создать правильно создать заголовочный файл для структур? Пытаюсь так, не выходит: structures.h

#ifndef LAB_8_STRUCTURES_H
#define LAB_8_STRUCTURES_H

struct Date;

struct Product;

#endif //LAB_8_STRUCTURES_H

structures.cpp

#include "structures.h"

struct Date {
    int day;
    int mon;
    int year;

    void init(int day, int mon, int year) {
        this->day = day;
        this->mon = mon;
        this->year = year;
    }

    long getDays() {
        int m[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

        long days = (year - 1) * 365 + (year - 1) % 4;
        for (int i = 0; i < mon; i++) {
            days += m[i];
        }
        if (mon >= 1)
            days++;
        days += day;

        return days;
    }
};

struct Product {
    char *name;
    float weight;
    float price;
    Date exp;

    void init(char *name, float weight, float price, Date exp) {
        this->name = name;
        this->weight = weight;
        this->price = price;
        this->exp = exp;
    }
};

#endif
1
  • А что именно у вас и откуда не выходит?
    – n3r0bi0m4n
    26 ноя 2017 в 7:10

1 ответ 1

2

Так, как написано у вас - все функции-члены определены в самом объявлении структур (т.е. являются inline) - все это и должно быть в заголовочном файле. Просто вместо

struct Date;
struct Product;

внесите в заголовочный файл все то, что идет после

#include "structures.h"

в structures.cpp - и пользуйтесь.

Вот если бы у вас в объявлении структуры было

struct Date {
    int day;
    int mon;
    int year;

    void init(int day, int mon, int year);
    long getDays();
};

то это объявление должно было бы находиться в заголовочном файле, а в .cpp-файле - реализация:

void Date::init(int day, int mon, int year) {
    this->day = day;
    this->mon = mon;
    this->year = year;
}

long Date::getDays() {
    int m[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

    long days = (year - 1) * 365 + (year - 1) % 4;
    for (int i = 0; i < mon; i++) {
        days += m[i];
    }
    if (mon >= 1)
        days++;
    days += day;

    return days;
}
1
  • Так как от автора текста ошибки не дождался, то было бы неплохо упомянуть. что это aggregate ... has incomplete type and cannot be defined для g++, а то по коду будет трудновато найти решение, если у кого-нибудь возникнет похожий вопрос. В VC++ не знаю как звучит ошибка.
    – n3r0bi0m4n
    26 ноя 2017 в 7:21

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.