简体   繁体   English

访问私有类C ++内部的结构

[英]Accessing a struct inside of a private class C++

I am lost in trying to figure out how to access this struct that is inside of the private part of the class. 我迷失在试图弄清楚如何访问该类私有部分内部的结构。 II would need the code to stay as a struct if that is possible. 如果可能的话,II将需要代码保留为结构。 Thanks very much for the help. 非常感谢您的帮助。

const int MAX_CHAR = 101;
const int NAME_COURSE_WIDTH = 20;
const int DESCRIPTION_WIDTH = 40;
const int DUE_DATE_WIDTH = 20;
const int COURSE_ENTRY_CAPACITY = 100;

class Task
{
private:
    struct CourseEntry
    {
        char course[MAX_CHAR];
        char description[MAX_CHAR];
        char dueDate[MAX_CHAR];
    } course;
public:


    void displayMenu();
    char readInCommand();
    void processCommand(char command, CourseEntry list[], int& listSize);
    void readInEntry(CourseEntry& anEntry);
    void readInCourse(char course[]);

    //database related functions
    void displayAll(const CourseEntry list[], int listsize); 
    void addEntry(const CourseEntry& anEntry, CourseEntry list[], int& listSize);
    bool searchEntry(const char course[], CourseEntry& match, const CourseEntry list[], int listSize);

    void loadCourseEntry(const char fileName[], CourseEntry list[], int& listSize);
    void saveCourseEntry(const char fileName[], const CourseEntry list[], int listSize);

    //standard input tools
    int readInt(const char prompt[]);
    void readString (const char prompt[], char inputStr[], int maxChar);
};

You should move the definition of the struct outside the class, and just keep the variable private: 您应该将结构的定义移到类之外,并且只将变量保持私有:

struct CourseEntry
{
    char course[MAX_CHAR];
    char description[MAX_CHAR];
    char dueDate[MAX_CHAR];
}

class Task {
    private:
       CourseEntry course;

    public:

        ...
}

It will be better and nicer and will keep encapsulation if you declare your CourseEntry structure public in the class Task and every time you use it just put the class name before like this Task::CourseEntry . 如果您在TaskCourseEntry结构声明为public ,它将更好,更好,并且将保持封装状态,并且每次使用它时,只需将类名放在前面,就像Task::CourseEntry

So for example a call in main will be (C++11 style): 例如, main的调用将是(C ++ 11样式):

 Task myTask;
 //initialize somehow your struct 
 Task::CourseEntry myStruct = {//here you can do it
                              };
 //call readInEntry
 myTask.readInEntry(myStruct);`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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