Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;:从父类中获取子成员_C++ - Fatal编程技术网

C++ C++;:从父类中获取子成员

C++ C++;:从父类中获取子成员,c++,C++,我最近问了一个问题,这个问题与使用cout方法从父类访问子成员有关。但是这次如果我想使用get方法而不是cout呢?这会改变想法吗? 假设我有一个叫做CArray的类: class CArray { public: CArray(); private: std::vector<CPerson *>Persons; }; 假设我们加载了CStudent和CPerson的私有成员,如下所示: if (condition) { CStudent *S1

我最近问了一个问题,这个问题与使用cout方法从父类访问子成员有关。但是这次如果我想使用get方法而不是cout呢?这会改变想法吗? 假设我有一个叫做CArray的类:

class CArray
{
 public:
  CArray(); 
  
 private:
  std::vector<CPerson *>Persons;  
};
假设我们加载了CStudent和CPerson的私有成员,如下所示:

if (condition)
  {
    CStudent *S1 = new CStudent();
    S1->load(src); //Load function is missing in class but ignore it 
    Persons.push_back(S1);
  }
最近,我学习了如何使用virtual方法访问CStudent和CPerson的私有成员,并通过添加到
CStudent类
下面的函数来访问:

void Print()
    {
        CPerson::Print();
        std::cout << MatriculationNr << "\n";
    }
void Print()
{
CPerson::Print();
标准::cout
如果我想从
Persons
的第一个元素中获取
入学分数
(作为示例),该怎么办

您将无法使用。无论如何,您所显示的代码都不能使用。
入学NR
仅存在于
CStudent
中,并且它是
私有的,因此只有
CStudent
可以访问它

cout getMatrikulNr();
无效,因为我们在这里尝试从子类获取函数,但这种方式不可行。我想应用与print()相同的行为,但这是不可能的,因为get方法将使用返回参数

您必须:

  • CPerson
    添加一个公共虚拟
    getMatrikulNr()
    方法,然后
    CStudent
    可以覆盖该方法,例如:

    class-CPerson
    {
    公众:
    ...
    虚拟整数getMatrikulNr()常量
    {
    返回0;
    }
    ...
    };
    C班学生:公共CPerson
    {
    公众:
    ...
    int getMatrikulNr()常量重写
    {
    返回入学编号;
    }
    私人:
    国际预科学院;
    };
    
    然后您可以根据需要使用
    Persons[i]->getMatrikulNr()

  • 将公共
    getMatrikulNr()
    方法添加到
    CStudent
    ,然后
    dynamic\u cast
    每个
    CPerson*
    指针,查看它是否指向
    CStudent
    对象,例如:

    class学生:公共CPerson
    {
    公众:
    ...
    int getMatrikulNr()常量
    {
    返回入学编号;
    }
    私人:
    国际预科学院;
    };
    
    CStudent*student=dynamic_cast(个人[i]);
    如果(学生){
    //根据需要使用student->getMatrikulNr()。。。
    }
    
if (condition)
  {
    CStudent *S1 = new CStudent();
    S1->load(src); //Load function is missing in class but ignore it 
    Persons.push_back(S1);
  }
void Print()
    {
        CPerson::Print();
        std::cout << MatriculationNr << "\n";
    }