1. 程式人生 > >c++ ,protected 和 private修飾的構造函數

c++ ,protected 和 private修飾的構造函數

return 訪問 mes ostream log 創建 name targe ios

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 }

c++ ,protected 和 private修飾的構造函數