C++多态与虚拟:Objects 实例化(Objects Instantiation)探究

一、Objects的创建 

  依据已有的class CPoint ,我们可以产生一个或多个object(对象),或者说是产生一个instance(实体):

CPoint aPoint(7.2); // aPoint._x 初始值为 7.2
aPoint.x(5.3); // aPoint._x 现值为 5.3

  这样的objects可能放在函数的stack之中(对象是在函数内部创建的,例如在函数的作用域内),也有可能放在程序的data segment中(对象是在函数外部创建的,例如在全局作用域或静态作用域内)。我们也可以这样来产生一个objects:

CPoint* pPoint = new CPoint(3.6); // pPoint->_x 初 值 为 3.6
pPoint->x(5.3); // pPoint->_x 现值为 5.3
delete pPoint;

  使用new operator产生的objects,是放在程序的heap(堆)之内。

  不管哪一种方式来产生objects,我们依据某个class产生一个object的动作称为instantiation(实例化)。object的诞生和死亡时,会自动调用class中特殊的member function,称为constructor 和 destructor。

  Constructor:object诞生时会自动调用的class member functions称为构造函数,此函数的命名必须与class相同,参数可以自定,没有返回值。class可以有一个以上的constructors,其中无参数的那个称为default constructor;只有一个参数,并且以该class为参数类型的,称为copy constructor。

  Destructor :object生命结束时会自动调用的class member function称为析构函数,一个class只能有一个destructor,没有参数,没有返回值,其命名必须与class相同,并以~为前置符号。

二、Objects 的生命Scope of Objects

    由于objects可能位于stack或heap或data segment之中,所以objects的生命周期就有差异。

  1. 放在stack之中的称为local objects,它的生命随着objects的产生产而开始,随着所在函数的执行结束而结束。

  2.放在data segment之中的称为gobal objects,它的生命随着程序的开(比程序进入点还早),随着程序的结束而结束。

  3.放 在heap之中的称为heap objects,它的生命随着new operator而开始,随着delete operator而结束。    

  下面这个例子出现了刚刚所提到的三种不同的生命周期的objects。从程序的执行结果,我们可以清楚的看到三种objects的生命范围。其中用到的constructors(构造函数)和destructors(析构函数)。這個例子出現剛剛所提的三種不同生命週期的 objects。從程式的執行結果,
我們可以清楚看到三種 objects 的生命範圍。其中用到的 constructors(建構式) destructors。

#include <iostream.h>
#include <string.h>
class CDemo
{
  public:
     CDemo(const char* str); // constructor
     ~CDemo(); // destructor
  private:
     char name[20];
};
 CDemo::CDemo(const char* str) // constructor
{
  strncpy(name, str, 20);
   cout << "Constructor called for " << name << '\n';
 }
CDemo::~CDemo() // destructor
{
   cout << "Destructor called for " << name << '\n';
}
void func()
{
   CDemo LocalObjectInFunc("LocalObjectInFunc"); 
  static CDemo StaticObject("StaticObject"); 
  CDemo* pHeapObjectInFunc = new CDemo("HeapObjectInFunc"); 
  cout << "Inside func" << endl; 
 }
CDemo GlobalObject("GlobalObject"); 
void main()
{
   CDemo LocalObjectInMain("LocalObjectInMain"); 
   CDemo* pHeapObjectInMain = new CDemo("HeapObjectInMain"); 
   cout << "In main, before calling func\n"; 
   func();
   cout << "In main, after calling func\n"; 
}

  执行结果如下(注意,上例有new的动作,却没有delete,是个错误示范):

1. Constructor called for GlobalObject 
2. Constructor called for LocalObjectInMain 
3. Constructor called for HeapObjectInMain 
4. In main, before calling func 
5. Constructor called for LocalObjectInFunc 
6. Constructor called for StaticObject 
7. Constructor called for HeapObjectInFunc 
8. Inside func 
9. Destructor called for LocalObjectInFunc 
10. In main, after calling func 
11. Destructor called for LocalObjectInMain 
12. Destructor called for StaticObject 
13. Destructor called for GlobalObject 

 

 

posted on 2024-04-27 20:32  阮春义  阅读(38)  评论(0编辑  收藏  举报

导航