一段简单的代码,运行下自己体会(Cpp与Cs析构函数)

Cpp代码:

 

// CppTest.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"

class tree
{
 int height;
public:
 tree(int initialHeight);
 ~tree();
 void grow(int years);
 void printsize();
};


tree::tree(int initialHeight)
  {
   height=initialHeight;
  }

tree::~tree()
  {
   puts("inside tree destructor");
   printsize();
  }

  void tree::grow(int years)
  {
   height+=years;
  }

  void tree::printsize()
  {
  printf("tree height is %d\n",height);
  }

void _tmain(int argc, _TCHAR* argv[])
{
 puts("before opening brace");
 {
 tree t(12);
 puts("after tree creation");
 t.printsize();
 t.grow(4);
 puts("before closing brace");
 }
 puts("after closing brace");

}

 C#代码:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSTest
{
    public class Tree
    {
        int height;

        public Tree(int initialHeight)
        {
            height = initialHeight;
        }

        ~Tree()
        {
            Console.WriteLine("inside tree destructor");
            printsize();
        }

        public void grow(int years)
        {
            height += years;
        }

        public void printsize()
        {
            Console.WriteLine("tree height is {0}",height);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("before openint brace");//原来C#这样写代码段也可以
            {
                Tree t=new Tree(12);
                Console.WriteLine("after tree creation");
                t.printsize();
                t.grow(4);
                Console.WriteLine("before closing brace");
            }
           
            Console.WriteLine("after closing brace");
        }
    }
}

不要忘记把想法写出来哦,哈哈。

 

posted on 2009-06-06 19:16  孙伊  阅读(308)  评论(0编辑  收藏  举报

导航