C++语法基础--句柄类

来源:互联网 发布:vb编程百度云 编辑:程序博客网 时间:2024/06/15 02:28
                    句柄类解决C++面向对象编程中不能使用对象支持面向对象编程(必须使用指针或引用才能获得动态绑定行为)的问题。

准备知识1:可以简单地认为编译器首先扫描类定义(而不是类实现),知道这个类有什么函数、函数的原型是什么、有什么成员变量,成员变量的类型是什么。然后,编译器才会编译其实现,因此类成员函数总能直接访问任何成员变量和函数
  Example:
    class A
{
public:
 void fun()
 {
  cout<<"fun()"<<endl;
 }
 
 void print()
 {
  fun();
  fun1();
//fun1()在后面定义,但是仍然能被调用
 }
 void fun1()
 {
 cout<<"fun1()"<<endl;
 }


};




 int main()
 {
 A a;
 a.print();
 
return 0;
 }


 Output:
   fun()
   fun1() 



准备知识2:类的合成复制构造函数只复制值(包括指针值)


class A
{
public:
 A(int i):x(i),p(new int(2))
 {
 
 }
 
 A* copy()
 {
  return new A(*this);
//调用合成复制构造函数
 }
 
 void print()
 {
 cout<<"x: "<<x<<endl;
 cout<<"*p: "<<*p<<endl;
 }
private:
int x;
int *p;
};




 int main()
 {
  A a(1);
  A *p=a.copy();
  p->print();

 
return 0;
 }


 output:
  x:1
  *p:2



准备知识3:智能指针,详见C++语法基础--智能指针

1.句柄类存储和管理基类指针,指针所指对象的类型既可以指向基类类型对象又可以指向派生类型对象
  
2.包装了继承层次的句柄的两个重要的设计因素
  *必须确定对复制控制做些什么
  *句柄类决定句柄接口屏蔽还是不屏蔽继承层次


3.指针型句柄

   *保证复制(赋值)对象时,将复制指针而不是复制对象

   注:绿色代码不分并非句柄类必须部分,只是为了验证句柄类工作是否正常

 Example:
  class base
{
public:
virtual void fun()
{
cout<<"base::fun()"<<endl;

}


virtual base* copy()
{
return new base(*this);
}
};


class derived:public base
{
public:
virtual void fun()
{
cout<<"derived::fun()"<<endl;

}


virtual derived* copy()
{
return new derived(*this);
}
};


class handle:public derived
{
public:
handle():pt(0),count(new size_t(1))
{
}

handle(base& other):pt(other.copy()),count(new size_t(1))
{

++*count;
}

handle& operator=(handle& other)
{
++*(other.count);

delete_handle();
pt=other.pt;
count=other.count;
return *this;
}

base& operator*()
{
if(pt)
{
return *pt;
}
cerr<<"derefference error!"<<endl;
}

base* operator->()
{
if(pt)
{
return pt;
}
cerr<<"error! handle has been deleted "<<endl;
}

~handle()
{
delete_handle();
}

void print()
{
cout<<"count: "<<*count<<endl;
}

private:
base *pt;
size_t *count;
void delete_handle()
{
if(--*count==0)
{
cout<<"delete_handle()"<<endl<<endl;
delete pt;
delete count;
}
}

};


int main()
{
base b;
derived d;
handle h1;
cout<<"afeter handle defult constructor(hand h1;): "<<endl;
h1.print();
cout<<endl;

handle h2(b);
cout<<"afeter handle copy constructor(hand h2(b);): "<<endl;
(*h2).fun();
h2.print();
cout<<endl;

handle h3(d);
cout<<"afeter handle copy constructor(hand h3(d);): "<<endl;
(*h3).fun();
h3.print();
cout<<endl;

h1=h3;
cout<<"afeter handle assignment constructor(h1=h3;): "<<endl;
(*h1).fun();
h1.print();
cout<<endl;

(*h3).fun();
h3.print();

return 0;
}


运行结果: