13_1理解基類中成員的訪問限定符和派生類的繼承方式
阿新 • • 發佈:2019-01-27
#include <iostream> #include <string> using namespace std; class StudentA //(1)修改studentA類中各資料成員和成員函式的訪問限定符為public時沒有出現錯誤,修改為private時顯示錯誤為error2248即私有成員不能再派生類內使用。 { public: StudentA(int n,string nam,char s); void showA(); ~StudentA( ) { } protected: int num; string name; char sex ; }; class StudentB: public StudentA //(2)將此處的繼承方式改為protected時,出現錯誤。即保護成員只能在類內使用不能再類外使用。 { public: StudentB(int n,string nam,char s,int a,string ad); void showB( ); ~StudentB( ) { } private: int age; string addr; }; StudentA::StudentA(int n,string nam,char s) { num=n; name=nam; sex=s; } void StudentA::showA() { cout<<"num: "<<num<<endl; cout<<"name: "<<name<<endl; cout<<"sex: "<<sex<<endl<<endl; } StudentB::StudentB(int n,string nam,char s,int a,string ad):StudentA(n,nam,s) { age=a; addr=ad; } void StudentB::showB( ) { cout<<"num: "<<num<<endl; cout<<"name: "<<name<<endl; cout<<"sex: "<<sex<<endl; cout<<"age: "<<age<<endl; cout<<"address: "<<addr<<endl<<endl; } int main( ) { StudentB stud1(10010,"Wang-li",'f',19,"115 Beijing Road,Shanghai"); StudentB stud2(10011,"Zhang-fun",'m',21,"213 Shanghai Road,Beijing"); StudentA stud3(20010,"He-xin",'m'); stud1.showB( ); stud2.showA( ); stud3.showA( ); return 0; } 執行結果: