在C ++中,我可以访问结构的私有变量,但不能访问子结构中的私有变量

时间:2016-04-19 18:48:25

标签: c++ struct

struct teachers
{
    private:
        int gradDate;
        int quote;
        string name;
        string school;
        struct smallBoard
        {
            private:
                vector<string> grade;
                vector<string> school;
                vector<string> emblem;
                vector<int> year;
        };
        smallBoard sb;
    public:
        static void retrieveInformation(vector<teachers> &_teachers);
        static void t_addInfo(vector<teachers> &_teachers, teachers teachers_);
        static void s_addInfo(vector<teachers::smallBoard> &_smallBoard, teachers::smallBoard smallBoard_);
};

我可以说

teachers tempt;  
tempt.name = "Bob";

但每当我尝试访问smallBoard结构中的任何变量时,它都会告诉我它是私有的。我假设我访问smallBoard的方法不正确,那么我该如何实现呢?

2 个答案:

答案 0 :(得分:3)

smallBoard内声明teachers作为嵌套类型并不会改变smallBoard仍然是自己的数据类型及其自己的访问规则这一事实。要让teachers访问smallBoard的私人成员,必须将teachers声明为friend的{​​{1}}。

smallBoard

此外,如果struct smallBoard { private: vector<string> grade; vector<string> school; vector<string> emblem; vector<int> year; friend struct teachers; }; 被声明为smallBoard类型的private,那么它就不能用于teachers的公共方法的参数,因为来电者永远不会访问或实例化teachers个对象。所以你必须公开smallBoard

smallBoard

答案 1 :(得分:-4)

struct smallBoard
{
    vector<string> grade;
    vector<string> school;
    vector<string> emblem;
    vector<int> year;
};

struct teachers
{
    private:
        int gradDate;
        int quote;
        string name;
        string school;
        smallBoard sb;
    public:
        static void retrieveInformation(vector<teachers> &_teachers);
        static void t_addInfo(vector<teachers> &_teachers, teachers teachers_);
        static void s_addInfo(vector<smallBoard> &_smallBoard, smallBoard smallBoard_);
};

我通过分离结构并在我的“主”结构中定义结构来修复它。编译好。