在子類中賦值父類中的私有成員
#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函數賦值父類私有數據
調用父輩成員函數直接賦值,無需再聲明,不然就會覆蓋