代码之家  ›  专栏  ›  技术社区  ›  성기덕

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

  •  0
  • 성기덕  · 技术社区  · 7 年前
    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类中,该类派生自女性,但女性也派生自患者。我想做的是在patient类中使用受保护的成员。没有错误,但当我运行程序时,它被吓坏了。作为参考,我使用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)中的成员变量??

    1 回复  |  直到 7 年前
        1
  •  0
  •   Daniel    7 年前

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

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