简体   繁体   中英

How do you have a struct as a private member in a class and creating a parameterized constructor/setter function for it?

I haven't seen questions about this so I hope this isn't a repeat, but I know you can have a struct as a private member of the class. There seems to be no eloquent way to have a parameterized constructor with a struct as private member. Then there becomes the problem of having a setter function for the struct private member. There seems to be no way to access the struct members through a setter function within the one class.

The header file for the Book class

// Book.h file
// Header file for the Book class

#ifndef BOOK_H
#define BOOK_H
#include <iostream>
#include "Date.h"


class Book {
private:
    std::string m_ISBN;
    std::string m_title;
    std::string m_author;
    Date m_date;
public:
    // constructor
    Book();
    Book(std::string, std::string, std::string, Date);
    void set_date(int, Month, int);

};

#endif

The header file for the Date struct

// Date.h file
// Header file for the Date struct

#ifndef DATE_H
#define DATE_H

enum class Month {
    jan = 1, feb, mar, april, may, june, july, aug, sep, oct, nov, dec, MAXMONTH
};

struct Date {
    int m_year { 1800 };
    Month m_month { Month::jan };
    int m_day { 1 };
};

#endif

And then here's my cpp file

// Book.cpp file

#include "Book.h"

Book::Book() 
    : m_ISBN { " " },
    m_title { " " },
    m_author { " " },
    m_date {1800, Month::jan, 1 }
    {

    }

    Book::Book(std::string ISBN, std::string title, std::string author, Date date)
        : m_ISBN { ISBN },
        m_title { title},
        m_author { author },
        m_date { date }
        {
            
        }

        void Book::set_date(int year, Month month, int day) {
            this->Date::m_year { year }; // error
            this->Date::m_month { month }; // error
            this->Date::m_day { day }; // error 
        }

The code works fine up until set_date , but even before that point. If you create a Book object with parameters, the way you do it seems unintuitive Book one {"random_ISBN", "random_title", "random_author", { 1800, Month::jan, 3} }; Having these nest curly braces seems suboptimal. You could create a Date struct and then pass that into it, but that seems wrong.

Replace

void Book::set_date(int year, Month month, int day) {
            this->Date::m_year { year }; // error
            this->Date::m_month { month }; // error
            this->Date::m_day { day }; // error 
        }

with

void Book::set_date(int year, Month month, int day) {
            m_date.m_year = year;
            m_date.m_month = month;
            m_date.m_day = day;
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM