随笔 - 7  文章 - 0  评论 - 0  阅读 - 360

C++学习(四)

对象继承
复制代码
 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 }
复制代码

 

 

posted on   斌仔16  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示