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

时间:2018-03-18 17:23:53

标签: c++ class inheritance member

abstract class Hideable {
    public hidden = [];
    public toJSON() {
        var result = {};
        for (var x in this) {
            if(x == "hidden") continue;
            if (this.hidden.indexOf(x) === -1) {
                result[x] = this[x];
            }
        }
        return result;
    };
}

这是我的代码,这个函数在FemaleIn类中,它源自Female,而Female也来自患者。我想要做的是我想在患者班中使用受保护的成员。没有错误,但是当我运行该程序时,它已经被搞砸了。作为参考,我使用矢量来存储基于患者类型的患者对象。像这个std :: vector病人

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;
}

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

1 个答案:

答案 0 :(得分:0)

根据您提供的代码,您似乎没有为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现在允许您从标准输入中读取字符串并将它们存储在每个成员变量中,并{{1 object将根据需要处理所有必要的内存分配(以及在不再使用时清理它)。然后,您应该能够使用函数std::string,因为语法是正确的。

除此之外,正如其他人所指出的,您可能想重新考虑您的类层次结构设计,但这不应该是一个问题。您还可能需要重新考虑如何存储某些类型的变量(例如,FemaleIn::enterPatientData可能更好地存储为age)。