c++ ,protected 和 private修饰的构造函数

 

 protected 和 private修饰的构造函数:连接

1. 在类的外部创建对象时,不能调用protected或private修饰的构造函数。

2.当子类中的构造函数调用父类的private构造函数时会错,当子类中的构造函数调用父类中的 public或protected构造函数时是对的

 1 #include <iostream>
 2 using namespace std;
 3 
 4 /****************************************************/
 5 class A {
 6 public:
 7     A();
 8 protected:
 9     A(int x);
10 private:
11     A(int x, int y);
12 };
13 
14 A::A() { cout<<"A::A() public"<<endl; }
15 A::A(int x) { cout<<"A(int x) protected"<<endl; }
16 A::A(int x, int y) { cout<<"A(int x,int y) private"<<endl;}
17 
18 /*******************************************************/
19 
20 class B: public A {
21 public:
22     B();
23     B(int x);
24     //B(int x , int y);
25     void show();
26 };
27 
28 B::B(): A() {} //public A()
29 
30 B::B(int x): A(x) {} //子类中的构造函数可调用父类的protected构造函数
31 
32 //当子类中的构造函数调用父类的private构造函数时会错
33 // error C2248: “A::A”: 无法访问 private 成员(在“A”类中声明)
34 // B::B(int x, int y): A(x,y) {}
35 
36 /*******************************************************/
37 void f1() 
38 {
39     A a1;         // A::A() public
40     //A a2(1);    //error:在类的外部创建对象时,不能调用protected或private修饰的构造函数。
41     //A a3(1,2);  //error:在类的外部创建对象时,不能调用protected或private修饰的构造函数。
42     B b1(33);     // A(int x) protected
43 }
44 
45 int main()
46 {
47     f1();
48     while(1);
49     return 0 ;
50 }

转载于:https://www.cnblogs.com/sunbines/p/10518075.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值