群里我师傅给我的答案:

unit Unit4;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type
  TForm4 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

  /// <summary>
  /// 我曾经容易犯的错误理解:
  ///    Tperson再全局静态内存中 肯定得有个实例 才能 调用 function啊
  ///
  /// 知识点:
  ///   类方法是不需要初始化实例的
  ///   创建实例的时候
  ///   不是的,class function 类似于全局函数,只是挂名在这个类下面
  ///   class function 是不能访问Self的
  ///   Self都没有,当然也不能访问成员变量了
  ///   class 是类的方面,没有实例,就没有self
  /// </summary>
  TPerson = class
    //类常量得写在这里
    const hehe1 = 'hehe1';
  private
    Fname: string;
    class var Fname1: string;
    procedure Setname(const Value: string);
    class procedure Setname1(const Value: string); static;
    public
      /// <summary>
      /// 实例方法
      /// </summary>
      function sayName(): string;

      /// <summary>
      /// 类方法----class function 类似于全局函数
      /// </summary>
      class function sayName1(): string;

      /// <summary>
      /// 实例变量
      /// </summary>
      var cde: string;

      /// <summary>
      /// 类变量-----按理说那就是全局变量了
      /// </summary>
      class var cde1: string;

      /// <summary>
      /// 实例常量
      /// </summary>
      const hehe = 'hehe';

      /// <summary>
      /// 类常量 ------ 全局常量了(但是不能写在这里,要写在上面,写在这里会报错)
      /// </summary>
      //class const hehe1 = 'hehe1';

      /// <summary>
      /// 实例属性
      /// </summary>
      property name: string read Fname write Setname;

      /// <summary>
      /// 类属性
      /// </summary>
      class property name1: string read Fname1 write Setname1;
  end;

var
  Form4: TForm4;

implementation

{$R *.dfm}


procedure TForm4.Button1Click(Sender: TObject);
begin
  //TPerson.cde := 'wokao';这句会报错,因为没有实例 无法访问实例的变量
  TPerson.cde1 := 'wokao';
  ShowMessage(TPerson.cde1);
  ShowMessage(TPerson.hehe);//这句竟然也可以
  ShowMessage(TPerson.hehe1);
  //ShowMessage(TPerson.name);这句不可以
  ShowMessage(TPerson.name1);
end;

{ TPerson }

function TPerson.sayName: string;
begin
  //实例方法即可以访问类属性也可以访问正常的属性
  name := 'wokao';
  name1 := 'wokao1';
end;

class function TPerson.sayName1: string;
begin
  //类方法只能访问类属性
  name1 := 'wokao1';
  //这里会报错,因为没有实例,所以不能访问实例的属性.
  //name := 'wokao';
end;

procedure TPerson.Setname(const Value: string);
begin
  Fname := Value;
end;

class procedure TPerson.Setname1(const Value: string);
begin
  Fname1 := Value;
end;

end.

 

posted on 2016-10-16 14:28  del88  阅读(496)  评论(0编辑  收藏  举报