9. 构造和析构

   class Point
   {
     public:
       void init(int x, int y);
       void print() const;
       void move(int dx, int dy);

     private:
       int x;
       int y;
   };

   Point a; //内存找了一个地方,放Point的对象 (对象搬进内存,C++不会将屋子打扫干净(成员变量值赋值0),原因是为了效率. a的成员变量值不确定)

   a.init(1,2);
   a.move(2,2);
   a.print();

//visual studio编译debug: 对象里填充一种东西,表示屋子还没有被初
//始化过,填充0xcd. 当2个0xcd连在一起的时候,恰好是”烫”. 没有初
//始化的内存.
//visual studio: 足迹分析. 没有初始化的内存是0xcd, 初始化的内存就
//不是0xcd.

构造函数

 class X
 {
    public:
    int i;
    X();//构造函数,对象创建的时候,自动被调用.
 }
  #include <stdio.h>
  class A
  {
    public:
      int i;
      A();
      void f();
  };

A::A() //构造函数
{
   i = 0; 
   printf("A::A()--this = %p\n",this); 
}
void A::f()
{
   this->i = 20;
   printf("A::f()--&i=%p\n",&i);
   printf("this = %p\n",this);
}

int main()
{
   A a; //自动调构造函数 A::A()--this = 0xbff1cc58
   A aa; //自动调构造函数 A::A()--this = 0xbff1cc50
   a.i = 10;
   printf("&a = %p\n",&a); //&a = 0xbff1cc58
   printf("&a.i = %p\n",&(a.i)); &a = 0xbff1cc58
   a.f(); //A::f()--&i= 0xbff1cc58, this = 0xbff1cc58
   printf("&aa = %p\n", &aa); //&aa = 0xbff1cc50
   aa.f(); //A::f()--&i= 0xbff1cc50, this = 0xbff1cc50
}

构造函数可以允许有参数,

class Tree
{
   public:
   Tree(int i);
}
int main()
{
  Tree t(12);//调构造函数,12传给i
}
#include <iostream>
using namespace std;

class Tree
{
  int height;
  public:
    Tree(int initialHeight);//构造函数
    ~Tree(); //析构函数
    void grow(int years);
    void printsize();
};

Tree::Tree(int initialHeight) //构造函数
{
   height = initialHeight;
   cout << "inside Tree::Tree()" << endl;
}
~Tree::Tree()
{
  cout << "inside Tree destructor" << endl;
  printsize();
}
void Tress::grow(int yeara)
{
  height += years;
}

void Tree::printsize()
{
  cout << "Tree height is " << height << endl;
}


int main()
{
  cout << "before opening brace" << endl;//before opening brace
  //{ 之前t不存在
  {
    Tree t(12); //inside Tree::Tree() 调构造函数
    cout << "after Tree creation" << endl; // after Tree creation
    t.printsize(); // Tree height is 12
    t.grow(4); 
    cout << "before closing brace" << endl; // before closing brace
               //inside Tree destructor 调析构函数
               //Tree height is 16
  }
  //}之后t也不存在
    cout << "after closing brace" << endl; //after closing brace
  return 0;
}

析构函数

函数被消灭的时候调用.

  class Y
  {
    public:
     Y(); //构造函数
     ~Y();//析构函数
  }

析构函数: 对象存在过程中,申请了一些资源. 用析构函数将申请的资源全部释放.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值