如何解决无法访问在头文件中声明的 cpp 文件中的私有结构
标题.h
Class A{
private:
struct Student
{
std::string name;
uint32_t rollno;
};
}
#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?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。