现在的位置: 首页 > 综合 > 正文

构造函数定义为private,protected (续)

2013年11月02日 ⁄ 综合 ⁄ 共 791字 ⁄ 字号 评论关闭

 

#include<iostream>

using namespace std;

class Base{
public:
     int b_data;
     friend Base& ConstructionClass(int);
private:
     Base(int data):b_data(data)
     {  
         cout << " construction class" << endl;
     }
     ~Base()
     {  
         cout << " deconstruction class " << endl;
     }
};

Base& ConstructionClass(int d)
{
     static Base base = Base(d);     
     return  base;
}   

int main(int argc, char **argv)
{
    cout << "===============" << endl;
    Base &section = ConstructionClass(100);
    cout << "===============" << endl;
   
    cout << "data value: " << section.b_data << endl;
   
    return 0;
}

程序通过友元函数访问private属性构造函数和西沟函数,编译:

g++ construction.cpp

运行:

./a.out

结果:

===============
 construction class
===============
data value: 100
 deconstruction class

总结:

若将构造和析构函数定义为private,则可以通过两种方式调用析构或者构造函数:

1、通过静态成员函数,见前一篇文章《构造函数定义为private,protected 》

2、友元函数,并且不能定义引用与指针。

 


 

抱歉!评论已关闭.