如果我无法访问字符串变量,如何检查 NULL(空/0) 字符串
How to check for NULL(empty/0) strings if I don't have access to the string variables
编辑:抱歉,如果我没有指定,我无法更改这些给定的结构和类。所以我无法为学生结构和成绩类中的字段制作获取/设置函数。
这是两部分的赋值,第 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%确定这是你的老师所期望的。
- 如何检查一个c++字符串中有多少相同的字符/数字
- 在编译时检查字符串文本的长度
- 检查字符串是否"null" C++
- 检查连续对的字符串C++
- 我应该如何解析和检查字符串?
- 检查字符串是否为整数
- 我遇到了这个代码片段,不明白. 它递归检查 C++ 字符串中是否存在大写字符
- 如何检查模板类中的变量是否为字符串类型?
- 检查数组中是否有字符串中的值,如果没有,则添加它
- C++ - 使用用户输入的字符串数据检查结构字符串数据(无限执行 while 循环)
- 字符串变成链表,然后检查括号余额
- 使用 SET(C++) 检查两个给定字符串是否是字谜时出现运行时错误
- 如何检查字符串中是否有重复的负号?例如 --1
- 如何检查字符串是否正确以将其转换为 int?
- 字符串检查总是返回假的Palidrome
- 自定义 {fmt} 格式化函数,具有编译时格式字符串检查功能
- 是否可以使用字符串检查预处理器定义
- NULL /空字符串检查:CPU开销
- 使用数组和无指针创建回文字符串检查器C++
- 使用constexpr进行基本编译时格式字符串检查