簡體   English   中英

您如何將結構作為 class 中的私有成員並為其創建參數化構造函數/設置器 function?

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

我還沒有看到關於這個的問題,所以我希望這不是重復,但我知道你可以擁有一個結構作為 class 的私有成員。 似乎沒有 eloquent 方法可以將帶有結構的參數化構造函數作為私有成員。 然后就出現了為結構私有成員設置設置器 function 的問題。 似乎無法通過一個 class 中的設置器 function 訪問結構成員。

圖書 class 的 header 文件

// 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

Date 結構的 header 文件

// 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

然后這是我的 cpp 文件

// 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 
        }

該代碼在set_date之前工作正常,但甚至在此之前。 如果您創建帶有參數的 Book object,您的操作方式似乎不直觀Book one {"random_ISBN", "random_title", "random_author", { 1800, Month::jan, 3} }; 擁有這些嵌套花括號似乎不是最理想的。 您可以創建一個 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 
        }

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;
        }

暫無
暫無

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

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