zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    【博弈论】取火柴游戏
    【贪心】马拉松接力赛
    【贪心】0/1背包
    【贪心】赶作业
    C# 设计模式 (一)
    C# 反射入门
    C# WinForm 访问webService天气预报
    WebService 测试地址
    C# Windows服务相关
    CSS 案例学习
  • 原文地址:https://www.cnblogs.com/sunbines/p/10518075.html
Copyright © 2011-2022 走看看