【问题标题】:Accessing protected members in derived class C++访问派生类 C++ 中的受保护成员
【发布时间】:2018-03-18 17:23:53
【问题描述】:
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 类中,该类派生自女性,但女性也派生自患者。我想做的是我想在病人类中使用受保护的成员。没有错误,但是当我运行程序时,它被吓坏了。作为参考,我使用向量来根据患者类型存储患者对象。像这样的 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;

};

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

【问题讨论】:

  • 女性来源于Patient?我已经有点担心你的等级制度了..
  • @miradulo 是的。它是从患者类派生的。这就像关系 A-B-C Patient-Female-FemaleIn
  • 顺便说一句,你不需要this-&gt;语法,直接访问成员。

标签: c++ class inheritance member


【解决方案1】:

仅根据您提供的代码,您似乎没有为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)。

【讨论】:

  • 非常感谢!顺便说一句,您应该能够按原样使用您的函数 FemaleIn::enterPatientData,因为语法是正确的。我不明白这个。
  • @성기덕 哦,我只是说您似乎不需要对FemaleIn::enterPatientData 进行任何更改来解决您的问题。您的问题出在Person 的类定义中。
猜你喜欢
  • 2018-11-27
  • 2012-05-26
  • 2016-04-07
  • 2023-03-18
  • 2014-08-27
  • 2013-10-21
  • 2013-09-17
相关资源
最近更新 更多