码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2014-11-13 18:40:37      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   os   sp   div   log   bs   

c++ 

protected 和 private修饰的构造函数:

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

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

 

#include <iostream>
using namespace std;


////////////////////////////////////////////////
class A {
public:
    A();
protected:
    A(int x);
private:
    A(int x, int y);
};
A::A() {
    cout<<"A::A() public"<<endl;
}
A::A(int x) {
    cout<<"A(int x) protected"<<endl;
}
A::A(int x, int y) {
    cout<<"A(int x,int y) private"<<endl;
}
////////////////////////////////////////////////
class B:public A {
public:
    B();
    B(int x);
    //B(int x , int y);
    void show();
};
B::B(): A() {//public A()

}
B::B(int x): A(x) {//子类中的构造函数可调用父类的protected构造函数

}

//当子类中的构造函数调用父类的private构造函数时会错
// error C2248: “A::A”: 无法访问 private 成员(在“A”类中声明)
// B::B(int x, int y): A(x,y){ 
// 
// }

////////////////////////////////////////////////
void f1() 
{
    A a1;            // A::A() public
    //    A a2(1);    //error:在类的外部创建对象时,不能调用protected或private修饰的构造函数。
    //    A a3(1,2);    //error:在类的外部创建对象时,不能调用protected或private修饰的构造函数。
    B b1(33);       // A(int x) protected
}

int main()
{
    f1();

    while(1);
    return 0 ;
}

 

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

标签:style   blog   io   color   os   sp   div   log   bs   

原文地址:http://www.cnblogs.com/mylinux/p/4095473.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!