您如何将结构作为类中的私有成员并为其创建参数化构造函数/setter 函数?

问题描述

我还没有看到有关此的问题,所以我希望这不是重复,但我知道您可以将结构作为类的私有成员。似乎没有雄辩的方法可以将结构体作为私有成员的参数化构造函数。然后就出现了为 struct private 成员设置 setter 函数的问题。似乎没有办法通过一个类中的 setter 函数访问结构体成员。

Book 类的头文件

// 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,Date);
    void set_date(int,Month,int);

};

#endif

Date 结构体的头文件

// 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 对象,您的操作方式似乎不直观 Book one {"random_ISBN","random_title","random_author",{ 1800,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,int day) {
            m_date.m_year = year;
            m_date.m_month = month;
            m_date.m_day = day;
        }

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...