public、private、protect继承

 

1. 只有D继承B的方式是public时,用户代码才能使用派生类向基类的转换;如果D继承B的方式是受保护的或者私有的,则用户代码不能使用该转换。

 1 #include <iostream>
 2 #define _COUT(str) std::cout << st r<<" ";
 3 #define _COUTL(str) std::cout << str << std::endl;
 4  
 5 class A
 6 {
 7 public:
 8     virtual void print()
 9     {
10         cout << "我是A" << endl;
11     }
12 };
13  
14 class B : public A
15 {
16 public:
17     void print()
18     {
19         cout << "我是B, pubic继承A" << endl;
20     }
21 };
22  
23 class C : private A
24 {
25 public:
26     void print()
27     {
28         cout << "我是C, private继承A" << endl;
29     }
30  
31 };
32  
33 int main()
34 {
35     A *p;
36     B b;
37     C c;
38     
39     p = &b;
40     p = &c; // error:Cannot cast 'C' to its private base class 'A'
41     p->print();   
42 }
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-10-03
  • 2021-04-25
  • 2022-12-23
  • 2022-12-23
  • 2022-02-08
  • 2021-04-12
猜你喜欢
  • 2021-10-13
  • 2022-12-23
  • 2022-12-23
  • 2021-07-19
  • 2022-12-23
  • 2022-12-23
  • 2021-07-05
相关资源
相似解决方案