如果我无法访问字符串变量,如何检查 NULL(空/0) 字符串

How to check for NULL(empty/0) strings if I don't have access to the string variables

本文关键字:字符串 检查 NULL 访问 变量 如果 何检查      更新时间:2023-10-16

编辑:抱歉,如果我没有指定,我无法更改这些给定的结构和类。所以我无法为学生结构和成绩类中的字段制作获取/设置函数。

这是两部分的赋值,第 1 部分相对容易,结构如下:

第 1 部分(学生.h) 不能更改

const unsigned int MAX_GRADES= 5;
struct Student
{
    char* studentText;
    unsigned int numSubjects;
    Grade grades[MAX_ANSWERS];
    Student():studentText(0){};
    ~Student();
};

然后在第 2 部分中更改为:

第 2 部分(学生.h) 无法更改

struct Student
    {
            static const unsigned int MAX_GRADES = 5;
            Student():studentText(0){;}
            Student(char*,unsigned int,Grade*);
            Student(Student&);
            ~Student();
            friend ostream& operator<<(ostream&,Student&);
    private:
        char* studentText;
        unsigned int numSubjects;
        Grade grades[MAX_GRADES];
    };

等级是一个带有私有字符串的类:

第 2 部分(等级.h) 无法更改

 class Grade
    {
        char* subject;
        bool pass;
    public: 
        Grade():subject(0){;}
        Grade(char*,bool);
        Grade(Grade&);
        ~Grade();
        Grade& operator=(Grade&);
        friend ostream& operator<<(ostream&,Grade&);
    };

变量 studentText 我曾经用来检查学生 [] 中是否为空,方法是使用:

if(students[j]->studentText==0)

现在已经变得私密,我无法从我的主线到达它。谁能指出我正确的方向。

我可以使用重载<<以某种方式获取学生文本并测试它是否为 0。

提前致谢

首先,我同意关于使用 std::string 的评论,而不是通过其文本字段确定学生是否为空。

但是,如果您坚持要从Student获取私有的文本字段,则可以为此添加一个公共方法,该方法也将返回字符串const char*
这对于您的Student结构来说足够安全。

const char* getStudentText() const {
    return studentText;
}

然后在类之外,您可以在 if 语句中使用它,如下所示:

if (students[j]->getStudentText() == NULL) ...

你可以做的另一件事更优雅一点(只是一点点),问学生它是否为空(使用一种方法) - 这样学生就持有逻辑,说空意味着文本字段是空的(稍微好一点的封装)。

您可以将此方法添加到Student结构中:

bool isEmpty() const {
    return studentText == NULL;
}

然后在课外问:

if (students[j]->isEmpty()) ...

编辑:在操作的评论之后

这真的很不幸,您无法编辑结构/类,并且仍然想知道私有字符串是否为空。这有点像双手背在身后编码。

无论如何,有一个适合您的情况的解决方案(无论它多么丑陋):

std::ostringstream oss;
oss << students[j];
std::string s = oss.str();
if (s.empty()) ...

您需要#include <sstream>.

好的,所以你需要访问一个私有变量,这就是你所做的。这是常见且良好的做法,相信我的话。在需要访问私有时执行此操作:

把这些东西放在main.cpp在你 #include"Student.h"之后:

template<typename T>
struct invisible
{
    static typename T::type value;
};
template<typename T>
typename T::type invisible<T>::value;
template<typename T, typename T::type P>
class construct_invisible
{
    construct_invisible(){ invisible<T>::value = P; }
    static const construct_invisible instance;
};
template<typename T, typename T::type P>
const construct_invisible<T, P> construct_invisible<T, P>::instance;
struct Student_studentText{ typedef char* Student::*type; };
template class construct_invisible<Student_studentText, &Student::studentText>;

您的状况如下所示:

if(students[j]->*invisible<Student_studentText>::value == 0)

根本不需要更改学生.h。我99%确定这是你的老师所期望的。