无法访问在头文件中声明的 cpp 文件中的私有结构

问题描述

标题.h

Class A{

private:
struct Student
    {
        std::string name;
        uint32_t rollno;
    };

}

代码文件.cpp

#include "Header.h"
namespace
{
     const A::Student students[] = {
     {"Luffy",1},{"Zoro",2},};
}

const A::Student 抛出一个错误,指出 Student 在 codefile.cpp 中不可访问。如何使在头文件中声明为私有变量的 struct Student 变量可在 cpp 文件的未命名命名空间中访问?

解决方法

Private 结构体和类的成员被称为“私有”,因为它们只能从类/结构体内部访问。

如果你想保持结构私有,尝试在类的构造过程中初始化它的值。 像这样:

#include <vector>
#include <string>
class A{
public:
//constructor for two students
    A(const std::string &student1,const int rollNo1,const std::string &student2,const int rollNo2){
        m_student.push_back(Student(student1,rollNo1));
        m_student.push_back(Student(student2,rollNo2));
        
    }
private:
    struct Student
        {
            std::string name;
            uint32_t rollno;
            //explicit constructor for the struct
            Student(const std::string &Name,const int rollNo){
                name = Name;
                rollno = rollNo;
            }
        };
    std::vector<Student>m_student; //we need some container to store the students in the class
};
//usage
int main()
{
    A myClassInstance("Luffy",1,"Nami",2);
return 0;
}

显然有更好的方法可以做到这一点,在可以添加成员的类中添加一个“addStudent”公共成员函数。 还要确保您出于正确的原因使用未命名的命名空间:-) 检查此线程:Why are unnamed namespaces used and what are their benefits?