对象继承
1 #include <iostream> 2 using namespace std; 3 4 class Person{ 5 public: 6 int age; 7 char * name; 8 Person(char * name, int age){} 9 }; 10 //类默认是私有的 11 //public:公开继承,不加public会导致 main()函数中 student.age无法引用 12 //private: 私有继承在类里面是可以拿到父类属性,但是在类外边不行 13 class Student : public Person{ 14 public: 15 Student(char * name, int age): Person(name,age){} 16 }; 17 18 19 int main(){ 20 Student student("王三",10); 21 student.age = 20; 22 cout << "age :"<< student.age <<endl; 23 return 0; 24 }多继承 c++中多继承存在二义性问题。例如:
1 #include <iostream> 2 3 using namespace std; 4 5 class BaseActivity1 { 6 public: 7 BaseActivity1(){} 8 void showInfo(){ 9 cout << " BaseActivity1 showInfo" <<endl; 10 } 11 }; 12 13 class BaseActivity2{ 14 public: 15 BaseActivity2(){} 16 void showInfo(){ 17 cout << " BaseActivity2 showInfo" <<endl; 18 } 19 }; 20 21 class MainActivity :public BaseActivity1,public BaseActivity2{ 22 //解决方案2 23 // void showInfo(){ 24 // cout << " MainActivity showInfo" <<endl; 25 // } 26 }; 27 28 29 int main(){ 30 MainActivity act; 31 //此行代码会报错,编译器不清楚到底执行的是base1还是base2的showInfo() 32 // act.showInfo(); 33 //解决方案1:指定父类的执行函数 low 34 act.BaseActivity1::showInfo(); 35 //方案2:可在子类中重写此函数 36 37 return 0; 38 }
虚继承(系统源码推荐使用) virtual: 虚关键字 A为顶层父类,B C 继承A, D继承B C。
1 #include <iostream> 2 3 using namespace std; 4 5 class Person{ 6 public: 7 int age; 8 }; 9 class Women :public Person{ 10 11 }; 12 13 class Men : public Person{ 14 15 }; 16 17 class Student :public Women,public Men{ 18 //第二种解决方案:子类重写 19 public: 20 int age; 21 }; 22 23 24 int main(){ 25 Student student; 26 //第一种解决方案 27 student.Women::age = 100; 28 cout << "age: "<< student.Women::age << endl; 29 return 0; 30 } 31 32 33 第3种解决方案:通过virtual 关键字() 34 #include <iostream> 35 36 using namespace std; 37 38 class Person{ 39 public: 40 int age; 41 }; 42 //通过virtual 关键字 43 class Women :virtual public Person{ 44 45 }; 46 47 class Men : virtual public Person{ 48 49 }; 50 51 class Student :public Women,public Men{ 52 53 }; 54 55 56 int main(){ 57 Student student; 58 student.age = 100; 59 cout <<"age " << student.age <<endl; 60 return 0; 61 }
标签:int,age,C++,class,学习,Person,Student,public From: https://www.cnblogs.com/wangybs/p/17483810.html