访问派生类C++中的受保护成员

Accessing protected members in derived class C++

本文关键字:受保护 成员 C++ 派生 访问      更新时间:2023-10-16
void FemaleIn::enterPatientData()
{
cout << "enter name ";
cin >> this->name;
cout << "enter your age ";
cin >> this->age;
cout << "enter your diagnosis ";
cin >> this->diagnosis;
cout << "enter your insurance name ";
cin >> this->insuranceName;
cout << "enter your insurance number ";
cin >> this->insuranceNumber;
}

这是我的代码,这个函数在 FemaleIn 类中,该类派生自 Female,但 Female 也派生自患者。我想做的是我想在患者类中使用受保护的成员。没有错误,但是当我运行程序时,它被脸红了。作为参考,我正在使用矢量来存储基于患者类型的患者对象。像这样 std::vector 患者

class FemaleIn: virtual public Female, virtual public Inpatient
{
public:
FemaleIn();
void parse();
void toString();
void enterPatientData();
protected:
private:
};
class Female: virtual public Patient
{
public:
Female();
protected:
private:
};
class Patient
{
public:
Patient();
virtual void parse();
virtual void toString();
virtual void enterPatientData();
protected:
char* name;
char* SSN;
char* insuranceName;
char* insuranceNumber;
char* age;
char* spouseName;
char* diagnosis;
};

我的问题是如何将派生类的每个值存储到基类(患者)中的成员变量?

仅根据您提供的代码,您似乎没有为char *成员变量分配任何内存以存储字符串。如果我的假设是正确的,那么您的程序将失败,因为它试图将字符串复制到未指向任何有效内存空间的指针中,这会导致未定义的行为。我将为您提供最小,最好,最安全的编辑,您可以进行这些编辑来解决您的问题。

class Patient
{
public:
Patient();
virtual void parse();
virtual void toString();
virtual void enterPatientData();
protected:
std::string name;
std::string SSN;
std::string insuranceName;
std::string insuranceNumber;
std::string age;
std::string spouseName;
std::string diagnosis;
};

将每个受保护成员变量的类型从char *更改为std::string现在将允许您从标准输入中读取字符串并将它们存储在每个成员变量中,并且std::string对象将根据需要处理所有必要的内存分配(以及在不再使用时清理它)。然后,您应该能够按原样FemaleIn::enterPatientData使用函数,因为语法是正确的。

除此之外,正如其他人指出的那样,您可能希望重新考虑您的类层次结构设计,但这在这里应该不是问题。您可能还需要重新考虑如何存储某些类型的变量(例如,age可能更好地存储为int)。