GVKun编程网logo

String的构造函数,拷贝构造函数、析构函数和赋值函数(string类的构造函数,析构函数,赋值函数)

11

本篇文章给大家谈谈String的构造函数,拷贝构造函数、析构函数和赋值函数,以及string类的构造函数,析构函数,赋值函数的知识点,同时本文还将给你拓展C#语法练习(11):类[三]-构造函数、析构

本篇文章给大家谈谈String的构造函数,拷贝构造函数、析构函数和赋值函数,以及string类的构造函数,析构函数,赋值函数的知识点,同时本文还将给你拓展C# 语法练习(11): 类[三] - 构造函数、析构函数、base、this、C#学习笔记整理_深入剖析构造函数、析构函数、C#构造函数、私有构造函数、静态构造函数与构造函数执行顺序、c#类—成员函数和封装及构造函数、析构函数、静态成员等相关知识,希望对各位有所帮助,不要忘了收藏本站喔。

本文目录一览:

String的构造函数,拷贝构造函数、析构函数和赋值函数(string类的构造函数,析构函数,赋值函数)

String的构造函数,拷贝构造函数、析构函数和赋值函数(string类的构造函数,析构函数,赋值函数)

 
已知类String的原型为:

class String
{
 public:
  String(const char *str = NULL); // 普通构造函数
  String(const String &other); // 拷贝构造函数
  ~ String(void); // 析构函数
  String & operate =(const String &other); // 赋值函数
 private:
  char *m_data; // 用于保存字符串
};

  解答:

//普通构造函数

String::String(const char *str)
{
 if(str==NULL)
 {
  m_data = new char[1]; // 得分点:对空字符串自动申请存放结束标志'/0'的空
  //加分点:对m_data加NULL 判断
  *m_data = '/0';
 }
 else
 {
  int length = strlen(str);
  m_data = new char[length+1]; // 若能加 NULL 判断则更好
  strcpy(m_data,str);
 }
}

// String的析构函数

String::~String(void)
{
 delete [] m_data; // 或delete m_data;
}

//拷贝构造函数

String::String(const String &other)    // 得分点:输入参数为const型
{
 int length = strlen(other.m_data);
 m_data = new char[length+1];     //加分点:对m_data加NULL 判断
 strcpy(m_data,other.m_data);
}

//赋值函数

String & String::operate =(const String &other) // 得分点:输入参数为const型
{
 if(this == &other)   //得分点:检查自赋值
  return *this;
 delete [] m_data;     //得分点:释放原有的内存资源
 int length = strlen( other.m_data );
 m_data = new char[length+1];  //加分点:对m_data加NULL 判断
 strcpy( m_data,other.m_data );
 return *this;         //得分点:返回本对象的引用
}

  剖析:

  能够准确无误地编写出String类的构造函数、拷贝构造函数、赋值函数和析构函数的 面试 者至少已经具备了C++基本功的60%以上!

  在这个类中包括了指针类成员变量m_data,当类中包括指针类成员变量时,一定要重载其拷贝构造函数、赋值函数和析构函数,这既是对C++程序员的基本要求,也是《Effective C++》中特别强调的条款。

  仔细学习这个类,特别注意加注释的得分点和加分点的意义,这样就具备了60%以上的C++基本功

C# 语法练习(11): 类[三] - 构造函数、析构函数、base、this

C# 语法练习(11): 类[三] - 构造函数、析构函数、base、this


构造函数与析构函数:
using System;

class MyClass
{
    private int FNum;
    public int Num { get { return FNum; } }

    /* 构造函数没有返回值, 无参的构造函数是默认的 */
    public MyClass()
    {
        this.FNum = 2009;
    }

    /* 可以有多个参数不同的构造函数 */
    public MyClass(int x)
    {
        this.FNum = x;
    }

    public MyClass(params int[] arr)
    {
        foreach (int i in arr) this.FNum += i;
    }

    /* 析构函数无参、无返回值、无访问修饰, 最多只能有一个 */
    ~MyClass()
    {
        //析构函数是自动调用的
    }
}

class Program
{
    static void Main()
    {
        MyClass obj1, obj2, obj3;

        obj1 = new MyClass();
        Console.WriteLine(obj1.Num); //2009

        obj2 = new MyClass(100);
        Console.WriteLine(obj2.Num); //100

        obj3 = new MyClass(1, 2, 3);
        Console.WriteLine(obj3.Num); //6

        Console.ReadKey();
    }
}

 
 
 
 
 

 

 

  
  

如果没有构造与析构函数, new 时将使用默认(或继承); 给一个私有的构造函数能阻止类被实例化:
using System;

class MyClass
{
    private MyClass() { }
    public static void Msg1() { Console.WriteLine("Msg1"); }
    public static void Msg2() { Console.WriteLine("Msg2"); }
}

class Program
{
    static void Main()
    {
        MyClass.Msg1(); //Msg1
        MyClass.Msg2(); //Msg2

        Console.ReadKey();
    }
}

 
 
 
 
 

 

 

  
  

如果一个类有了非默认的构造函数, 就不能再使用默认的构造函数:
using System;

class MyClass
{
    private int FNum;
    public int Num { get { return FNum; } }

    public MyClass(int x, int y)
    {
        this.FNum = x + y;
    }
}

class Program
{
    static void Main()
    {
        MyClass obj;

        obj = new MyClass(1, 2);
        Console.WriteLine(obj.Num); //3

        Console.ReadKey();
    }
}

 
 
 
 
 

 

 

  
  

静态构造函数:

静态构造函数既无访问修饰符、无参数;
在 new 或调用任何静态成员之前,将自动调用静态构造函数;
静态构造函数一般用于初始化静态数据;
静态构造函数会在第一次 new 或第一次使用静态成员前触发;
不能直接调用静态构造函数.
using System;

class MyClass
{
    public static int Num;
    public static void ShowNum() { Console.WriteLine(Num); }
    public void Msg() { Console.WriteLine("Msg"); }

    static MyClass() { Num = 123; }
}

class Program
{
    static void Main()
    {
        MyClass.ShowNum();            //123
        MyClass.Num = 2009;
        MyClass.ShowNum();            //2009

        MyClass obj1 = new MyClass();
        obj1.Msg();                   //Msg

        Console.ReadKey();
    }
}

 
 
 
 
 

 

 

  
  

自动调用父类的构造方法:
using System;

class Parent
{
    public Parent() { Console.WriteLine("Parent"); }
}

class Child1 : Parent
{
    public Child1() { Console.WriteLine("Child1"); }
    public Child1(int x) { Console.WriteLine(x); }
}

class Child2 : Child1
{
    public Child2() { Console.WriteLine("Child2"); }
    public Child2(int x, int y) { Console.WriteLine(x + y); }
}

class Program
{
    static void Main()
    {
        Parent p = new Parent();           // Parent
        Child1 c1 = new Child1();          // Parent / Child1
        Child2 c2 = new Child2();          // Parent / Child1 / Child2

        Child1 c11 = new Child1(999);      // Parent / 999
        Child2 c22 = new Child2(111, 222); // Parent / Child1 / 333
        
        Console.ReadKey();
    }
}

 
 
 
 
 

 

 

  
  

base:
using System;

class Parent
{
    public Parent() { Console.WriteLine("Parent"); }
    public Parent(int x, int y) { Console.WriteLine(x + y); }
    public Parent(string s1, string s2) { Console.WriteLine(s1 + s2); }
}

class Child1 : Parent
{
    public Child1() { Console.WriteLine("Child1"); }
}

class Child2 : Parent
{
    public Child2() : base() { Console.WriteLine("Child2"); }
}

class Child3 : Parent
{
    public Child3() : base(111,222) { Console.WriteLine("Child3"); }
}

class Child4 : Parent
{
    public Child4() : base("111", "222") { Console.WriteLine("Child4"); }
}

class Program
{
    static void Main()
    {
        Child1 c1 = new Child1(); // Parent / Child1
        Child2 c2 = new Child2(); // Parent / Child2
        Child3 c3 = new Child3(); // 333 / Child3
        Child4 c4 = new Child4(); // 111222 / Child4
        
        Console.ReadKey();
    }
}

 
 
 
 
 

 

 

  
  

this:
using System;

class MyClass
{
    private string fs = "ABC-";
    public MyClass() { Console.WriteLine("MyClass"); }
    public MyClass(string str) { Console.WriteLine(this.fs + str); }
    public MyClass(int num) : this() { Console.WriteLine(num); }
    public MyClass(int x, int y) : this("XYZ") { Console.WriteLine(x + y); }
}

class Program
{
    static void Main()
    {
        MyClass c1 = new MyClass();          // MyClass
        MyClass c2 = new MyClass("EFG");     // ABC-EFG
        MyClass c3 = new MyClass(123);       // MyClass / 123
        MyClass c4 = new MyClass(111, 222);  // ABC-XYZ / 333
        Console.ReadKey();
    }
}

 
 
 
 
 

 

 

  
  

构造函数、属性、base:
using System;

abstract class Parent
{
    private byte FID;

    public Parent(byte n)
    {
        FID = n;
    }

    public byte Id
    {
        get { return FID; }
        set { FID = value; }
    }
}

class Child : Parent
{
    public Child(byte MyID) : base(MyID) { }
}


class Program
{
    static void Main()
    {
        Child Rect = new Child(6);
        Console.WriteLine(Rect.Id); //6

        Rect.Id = 8;
        Console.WriteLine(Rect.Id); //8

        Console.ReadKey();
    }
}

 
 
 
 
 

 

 

  
  

C#学习笔记整理_深入剖析构造函数、析构函数

C#学习笔记整理_深入剖析构造函数、析构函数

构造函数、析构函数

构造函数:

1.若没提供任何构造函数,则系统会自动提供一个默认的构造函数,初始化所有成员为默认值(引用类型为空引用null,值类型为0,bool类型为false);

2.若提供了带参数的构造函数,则系统不提供默认的构造函数;

3.构造函数可重载:可提供多个不同版本的构造函数,依据参数的个数、类型来区分;

4.私有构造函数:则无法通过该构造函数实例化该对象,可通过调用静态函数来实例化;当仅用作某些静态成员或属性的容器时,可定义私有构造函数来防止被实例化;

一般的构造函数都是实例构造函数,只要创建实例,就执行构造函数;

静态构造函数:

1.只能定义一个,最多运行一次,仅在第一次调用类的任何成员之前由.NET运行库调用它,

2.它不能带任何参数、无任何访问修饰符,只能访问类的静态成员,无法访问到类的实例成员;

3.如果类有一些静态字段、属性需要在第一次使用类之前从外部源中初始化,则使用静态构造函数;

4.静态构造函数与无参数的实例构造函数可以同时定义,何时执行哪个构造函数不会冲突;

在构造函数中可以调用自身的其它构造函数:this(),或父类的构造函数:base(),可类似继承的语法调用其它构造函数;

只读字段readonly:和常量const类似,不能修改其值,但只读字段用readonly声明,可以未初始化,在构造函数中对其初始化,之后不可更改其值;

匿名类型的实例化:var a = new{f1=“1ad”,f2=”34”,f3=5,f4=6};

构造函数:用于析构类的实例

• 不能在结构中定义析构函数。只能对类使用析构函数。

• 一个类只能有一个析构函数。

• 无法继承或重载析构函数。

• 无法调用析构函数。它们是被自动调用的。由垃圾回收器控制,如果垃圾回收器认为某个对象符合析构,则调用析构函数(如果有)并回收用来存储此对象的内存。程序退出时也会调用析构函数

• 析构函数既没有修饰符,也没有参数

可以通过调用 Collect 强制进行垃圾回收,但大多数情况下应避免这样做,因为这样会导致性能问题

C# 无需太多的内存管理。这是因为 .NET Framework 垃圾回收器会隐式地管理对象的内存分配和释放。但是,当应用程序封装窗口、文件和网络连接这类非托管资源时,应当使用析构函数释放这些资源。当对象符合析构时,垃圾回收器将运行对象的 Finalize 方法。

如果您的应用程序在使用昂贵的外部资源,我们还建议您提供一种在垃圾回收器释放对象前显式地释放资源的方式。可通过实现来自 Idisposable 接口的 dispose 方法来完成这一点,该方法为对象执行必要的清理。这样可大大提高应用程序的性能。即使有这种对资源的显式控制,析构函数也是一种保护措施,可用来在对 dispose 方法的调用失败时清理资源

class Car

{

  -Car() 

  {

    // … …

  }

}

该析构函数隐式地对继承链中的所有实例递归地调用调用 Finalize()方法

public class Bus
 {
   protected static readonly DateTime globalStartTime;
 
   protected int RouteNumber { get; set; }
 
   static Bus() //静态构造函数
   {
 globalStartTime = DateTime.Now;
 Console.WriteLine("Static ctor sets global start time to {0}",globalStartTime.ToLongTimeString());
   }
 
   public Bus(int routeNum)
   {
 RouteNumber = routeNum;
 Console.WriteLine("{0} is created.",RouteNumber);
   }
 
   public void Drive()
   {
 TimeSpan elapsedtime = DateTime.Now - globalStartTime;
 
 Console.WriteLine("{0} is starting its route {1:N2} minutes after global start time {2}.",this.RouteNumber,elapsedtime.TotalMilliseconds,globalStartTime.ToShortTimeString());
   }
 }
 
 class TestBus
 {
   static void Main()
   {
 
 Bus bus = new Bus(71);
 bus.Drive();
 System.Threading.Thread.Sleep(25);
 
 Bus bus2 = new Bus(72);
 bus2.Drive();
 
 System.Console.WriteLine("Press any key to exit.");
 System.Console.ReadKey();
   }
 }
 /* Output:
   Static ctor sets global start time to 10:04:08 AM
   71 is created.
   71 is starting its route 21.00 minutes after global start time 10:04 AM.
   72 is created.
   72 is starting its route 46.00 minutes after global start time 10:04 AM.   
*/

以上就是小编为大家带来的C#学习笔记整理_深入剖析构造函数、析构函数的全部内容了,希望对大家有所帮助,多多支持编程小技巧~

C#构造函数、私有构造函数、静态构造函数与构造函数执行顺序

C#构造函数、私有构造函数、静态构造函数与构造函数执行顺序

https://www.cnblogs.com/ArtofDesign/p/3603986.html

 默认构造函数,如果没有为类指定任何构造函数,编译器会自动为类创建一个无参构造函数,用以初始化类的字段;如果为类编写了构造函数,那么编译器就不会再自动生成无参构造函数了。ps.C#不允许用户为结构定义无参构造函数。

 

    静态构造函数,不能访问实例成员,只能用来初始化一些静态字段或者属性,仅在第一次调用类的任何成员时自动执行,不带访问修饰符,不带任何参数,每个类只能有一个静态构造函数,但可以同时还有一个无参实例构造函数,如下。

public class Demo
{
    static Demo() { }
    public Demo() { }
}

   

    私有构造函数,将构造函数申明为私有的,则不能通过new运算符在外部代码中实例化(但可以编写一个静态方法或属性在其内部实例化一个对象,再将结果返回给外部代码)。私有构造函数的作用:

  • 永远不会实例化,因为它仅用作某些静态成员的容器
  • 希望类只能通过调用某个静态方法来实例化(即所谓的对象实例化的类工厂方法)
复制代码
public class Demo
    {
        private Demo() { }
        public static Demo NewDemo()
        {
            return new Demo();
        }
    }
复制代码

 

    构造函数执行顺序,通常情况下:构造函数先调用System.Object的构造函数,再按照继承的层次结构从上往下进行,直到最终要实例化的类为止,即最先调用的是基类的构造函数,但如果类有静态构造函数,且为首次调用该类,则先调用的是子类的静态构造函数,再是父类的静态构造函数,当然静态构造函数只会执行这一次,如下

复制代码
//父类
public class SuperClass
{
    static SuperClass() 
    {
        Console.WriteLine("Super.Static");
    }
    public SuperClass() 
    {
        Console.WriteLine("Super.Instance");
    }
}

//子类
public class ChildClass : SuperClass
{
    static ChildClass() 
    {
        Console.WriteLine("Child.Static");
    }
    public ChildClass() 
    {
        Console.WriteLine("Child.Instance");
    }
}

//客户程序
class Program
{
    static void Main(string[] args)
    {
        ChildClass cc = new ChildClass();
        Console.ReadKey();
    }
}
复制代码

输出结果为:

Child.Static

Super.Static

Super.Instance

Child.Instance

 

    在不考了静态构造函数的情况下(因为静态构造仅执行一次,且定义静态构造函数的时候并不多),子类在调用父类的构造函数时,默认情况是调用父类的无参构造函数,如果父类只有带参构造函数,而没有无参构造函数,那么编译时会报错;不过我们可以通过base关键字来指定调用带参构造函数,如下

复制代码
//父类
public class SuperClass
{
    public SuperClass(string param)
    {
        Console.WriteLine("Super:" + param);
    }
}

//子类
public class ChildClass : SuperClass
{
    public ChildClass(string param):base(param)
    {
        Console.WriteLine("Child:" + param);
    }
}

//客户程序
class Program
{
    static void Main(string[] args)
    {
        ChildClass cc = new ChildClass("param");
        Console.ReadKey();
    }
}
复制代码

输出结果为

Super:param

Child:param

public class SuperStaticConstructor
    {
        public SuperStaticConstructor()
        {
            Console.WriteLine("parent constructor");
        }

        static SuperStaticConstructor()
        {
            Console.WriteLine("parent static constructor");
        }
    }
    public class StaticConstructor: SuperStaticConstructor
    {
        public StaticConstructor()
        {
            Console.WriteLine("child constructor");
        }

        static StaticConstructor()
        {
            Console.WriteLine("child static constructor");
        }
    }

    public class StaticConstructorTest
    {
        public static void Run()
        {
            string[] strArray = new string[4]{ "a","b", "a", "b" };
            Parallel.ForEach(strArray, (item) =>
            {
                Console.WriteLine(item);
                new StaticConstructor();
            });
        }
    }

  StaticConstructorTest.Run();

 

c#类—成员函数和封装及构造函数、析构函数、静态成员

c#类—成员函数和封装及构造函数、析构函数、静态成员

C# 类(Class)

当您定义一个类时,您定义了一个数据类型的蓝图。这实际上并没有定义任何的数据,但它定义了类的名称意味着什么,也就是说,类的对象由什么组成及在这个对象上可执行什么操作。对象是类的实例。构成类的方法和变量成为类的成员。

类的定义

类的定义是以关键字 class 开始,后跟类的名称。类的主体,包含在一对花括号内。下面是类定义的一般形式:

<access specifier> class  class_name 
{
    // member variables
    <access specifier> <data type> variable1;
    <access specifier> <data type> variable2;
    ...
    <access specifier> <data type> variableN;
    // member methods
    <access specifier> <return type> method1(parameter_list) 
    {
        // method body 
    }
    <access specifier> <return type> method2(parameter_list) 
    {
        // method body 
    }
    ...
    <access specifier> <return type> methodN(parameter_list) 
    {
        // method body 
    }
}

请注意:

  • 访问标识符 <access specifier> 指定了对类及其成员的访问规则。如果没有指定,则使用默认的访问标识符。类的默认访问标识符是 internal,成员的默认访问标识符是 private
  • 数据类型 <data type> 指定了变量的类型,返回类型 <return type> 指定了返回的方法返回的数据类型。
  • 如果要访问类的成员,您要使用点(.)运算符。
  • 点运算符链接了对象的名称和成员的名称。

下面的实例说明了目前为止所讨论的概念:

using System;
namespace BoxApplication
{
    class Box
    {
       public double length;   // 长度
       public double breadth;  // 宽度
       public double height;   // 高度
    }
    class Boxtester
    {
        static void Main(string[] args)
        {
            Box Box1 = new Box();        // 声明 Box1,类型为 Box
            Box Box2 = new Box();        // 声明 Box2,类型为 Box
            double volume = 0.0;         // 体积

            // Box1 详述
            Box1.height = 5.0;
            Box1.length = 6.0;
            Box1.breadth = 7.0;

            // Box2 详述
            Box2.height = 10.0;
            Box2.length = 12.0;
            Box2.breadth = 13.0;
           
            // Box1 的体积
            volume = Box1.height * Box1.length * Box1.breadth;
            Console.WriteLine("Box1 的体积: {0}",  volume);

            // Box2 的体积
            volume = Box2.height * Box2.length * Box2.breadth;
            Console.WriteLine("Box2 的体积: {0}", volume);
            Console.ReadKey();
        }
    }
}

当上面的代码被编译和执行时,它会产生下列结果:

Box1 的体积: 210
Box2 的体积: 1560

成员函数和封装

类的成员函数是一个在类定义中有它的定义或原型的函数,就像其他变量一样。作为类的一个成员,它能在类的任何对象上操作,且能访问该对象的类的所有成员。

成员变量是对象的属性(从设计角度),且它们保持私有来实现封装。这些变量只能使用公共成员函数来访问。

让我们使用上面的概念来设置和获取一个类中不同的类成员的值:

using System;
namespace BoxApplication
{
    class Box
    {
       private double length;   // 长度
       private double breadth;  // 宽度
       private double height;   // 高度
       public void setLength( double len )
       {
            length = len;
       }

       public void setBreadth( double bre )
       {
            breadth = bre;
       }

       public void setHeight( double hei )
       {
            height = hei;
       }
       public double getVolume()
       {
           return length * breadth * height;
       }
    }
    class Boxtester
    {
        static void Main(string[] args)
        {
            Box Box1 = new Box();        // 声明 Box1,类型为 Box
            Box Box2 = new Box();        // 声明 Box2,类型为 Box
            double volume;              // 体积


            // Box1 详述
            Box1.setLength(6.0);
            Box1.setBreadth(7.0);
            Box1.setHeight(5.0);

            // Box2 详述
            Box2.setLength(12.0);
            Box2.setBreadth(13.0);
            Box2.setHeight(10.0);
       
            // Box1 的体积
            volume = Box1.getVolume();
            Console.WriteLine("Box1 的体积: {0}" ,volume);

            // Box2 的体积
            volume = Box2.getVolume();
            Console.WriteLine("Box2 的体积: {0}", volume);
           
            Console.ReadKey();
        }
    }
}

当上面的代码被编译和执行时,它会产生下列结果:

Box1 的体积: 210
Box2 的体积: 1560

C# 中的构造函数

类的 构造函数 是类的一个特殊的成员函数,当创建类的新对象时执行。

构造函数的名称与类的名称完全相同,它没有任何返回类型。

下面的实例说明了构造函数的概念:

 

using System;
namespace LineApplication
{
   class Line
   {
      private double length;   // 线条的长度
      public Line(double len)  // 参数化构造函数
      {
         Console.WriteLine("对象已创建,length = {0}", len);
         length = len;
      }

      public void setLength( double len )
      {
         length = len;
      }
      public double getLength()
      {
         return length;
      }

      static void Main(string[] args)
      {
         Line line = new Line(10.0);
         Console.WriteLine("线条的长度: {0}", line.getLength()); 
         // 设置线条长度
         line.setLength(6.0);
         Console.WriteLine("线条的长度: {0}", line.getLength()); 
         Console.ReadKey();
      }
   }
}

当上面的代码被编译和执行时,它会产生下列结果:

对象已创建,length = 10
线条的长度: 10
线条的长度: 6

C# 中的析构函数

类的 析构函数 是类的一个特殊的成员函数,当类的对象超出范围时执行。

析构函数的名称是在类的名称前加上一个波浪形(~)作为前缀,它不返回值,也不带任何参数。

析构函数用于在结束程序(比如关闭文件、释放内存等)之前释放资源。析构函数不能继承或重载。

下面的实例说明了析构函数的概念:

using System;
namespace LineApplication
{
   class Line
   {
      private double length;   // 线条的长度
      public Line()  // 构造函数
      {
         Console.WriteLine("对象已创建");
      }
      ~Line() //析构函数
      {
         Console.WriteLine("对象已删除");
      }

      public void setLength( double len )
      {
         length = len;
      }
      public double getLength()
      {
         return length;
      }

      static void Main(string[] args)
      {
         Line line = new Line();
         // 设置线条长度
         line.setLength(6.0);
         Console.WriteLine("线条的长度: {0}", line.getLength());           
      }
   }
}

当上面的代码被编译和执行时,它会产生下列结果:

对象已创建
线条的长度: 6
对象已删除

C# 类的静态成员

我们可以使用 static 关键字把类成员定义为静态的。当我们声明一个类成员为静态时,意味着无论有多少个类的对象被创建,只会有一个该静态成员的副本。

关键字 static 意味着类中只有一个该成员的实例。静态变量用于定义常量,因为它们的值可以通过直接调用类而不需要创建类的实例来获取。静态变量可在成员函数或类的定义外部进行初始化。您也可以在类的定义内部初始化静态变量。

下面的实例演示了静态变量的用法:

using System;
namespace StaticVarApplication
{
    class StaticVar
    {
       public static int num;
        public void count()
        {
            num++;
        }
        public int getNum()
        {
            return num;
        }
    }
    class StaticTester
    {
        static void Main(string[] args)
        {
            StaticVar s1 = new StaticVar();
            StaticVar s2 = new StaticVar();
            s1.count();
            s1.count();
            s1.count();
            s2.count();
            s2.count();
            s2.count();         
            Console.WriteLine("s1 的变量 num: {0}", s1.getNum());
            Console.WriteLine("s2 的变量 num: {0}", s2.getNum());
            Console.ReadKey();
        }
    }
}

当上面的代码被编译和执行时,它会产生下列结果:

s1 的变量 num: 6
s2 的变量 num: 6

您也可以把一个成员函数声明为 static。这样的函数只能访问静态变量。静态函数在对象被创建之前就已经存在。下面的实例演示了静态函数的用法:.

using System;
namespace StaticVarApplication
{
    class StaticVar
    {
       public static int num;
        public void count()
        {
            num++;
        }
        public static int getNum()
        {
            return num;
        }
    }
    class StaticTester
    {
        static void Main(string[] args)
        {
            StaticVar s = new StaticVar();
            s.count();
            s.count();
            s.count();                   
            Console.WriteLine("变量 num: {0}", StaticVar.getNum());
            Console.ReadKey();
        }
    }
}
变量 num: 3

 

今天的关于String的构造函数,拷贝构造函数、析构函数和赋值函数string类的构造函数,析构函数,赋值函数的分享已经结束,谢谢您的关注,如果想了解更多关于C# 语法练习(11): 类[三] - 构造函数、析构函数、base、this、C#学习笔记整理_深入剖析构造函数、析构函数、C#构造函数、私有构造函数、静态构造函数与构造函数执行顺序、c#类—成员函数和封装及构造函数、析构函数、静态成员的相关知识,请在本站进行查询。

本文标签: