2020/04/30作业

在子类中赋值父类中的私有成员

#include<iostream>
#include<cstring>
using namespace std;
class person{
    public:
       void set_p(string n,int a,string s){name=n;age=a;sex=s;}
       void display_p()
        {cout<<"name is "<<name<<" age is "<<age<<"sex is"<<sex<<endl;}
    private:
        string name;
        int age;
        string sex;
};
class student:public person
{
    int xh;
    int bj;
    string zy;
    double cj;
    public:        //错误示范如下
   void set_t(string k,int m,string f,int a,int b,string c,double d)
    {person::name=k;person::age=m;person::sex=f;xh=a;bj=b;zy=c;cj=d;}
   void display_s()
    {cout<<person::name<<" "<<person::age<<" "<<person::sex<<" "<<xh<<" "<<bj<<" "<<zy<<cj;}
};
。。。。。。。

在这里插入图片描述
这里提示数据为私有数据
就是说父类中的私有数据只能通过父类的函数赋值,子类不能直接访问父类的私有数据
应该为如下

public:
   void set_t(string k,int m,string f,int a,int b,string c,double d)
    {set_p(k,m,f);xh=a;bj=b;zy=c;cj=d;}
   void display_s()
    {display_p();
    cout<<" "<<xh<<" "<<bj<<" "<<zy<<cj;}

于子类中调用父类的set_p函数赋值父类私有数据

调用父辈成员函数直接赋值,无需再声明,不然就会覆盖
在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章