zoukankan      html  css  js  c++  java
  • C++——继承时的this指针


    1.this指针只在类的成员函数中使用,当类的成员函数需要用到自己的指针时就要用到this指针。但静态函数不能使用this关键字,其解释是:因为this是个引用,哪个对象调用方法就引用哪个对象。 而静态方法有可能不是被对象调用的,this无从引用,也就是:静态方法是属于整个类的,this指的是当前的对象。比如:
    class ExamThis
    {
    int ShowThis() //定义一个显示自己指针的成员函数。
    {
    printf(“This is my this pointer %x “, this);
    }
    };

    2.this的另一个用途是调用当前对象的另一个构造函数 ;

    3.在你的方法中的某个形参名与当前对象的某个成员有相同的名字,这时为了不至于混淆,你便需要明确使用this关键字来指明你要使用某个成员,使用方法是 “this.成员名” ,而不带this的那个便是形参。

    4.this后加参数则调用的是当前类具有相同参数的构造函数
    class Person{
    public static void prt(String s){
    System.out.println(s);
    }
    Person(){
    prt(A Person.);
    }
    Person(String name){
    prt(A person name is+name);
    }
    }
    public class Chinese extends Person{
    Chinese(){
    super(); //调用父类构造函数(1)
    prt(A chinese.); //(4)
    }
    Chinese(String name){
    super(name); //调用父类具有相同形参的构造函数(2)
    prt(his name is+name);
    }
    Chinese(String name,int age){
    this(name); //调用当前类具有相同形参的构造函数(3)
    prt(his age is+age);
    }
    public static void main(String[] args){
    Chinese cn=new Chinese();
    cn=new Chinese(kevin);
    cn=new Chinese(kevin,22);
    }
    }

    在构造函数中this用于限定被相同的名称隐藏的成员,例如:
    class Employee{
    public Employee(string name, string alias) {
    this.name = name;
    this.alias = alias;
    }
    }

    将对象作为参数传递到其他方法时也要用this表达,例如:
    CalcTax(this);

    声明索引器时this更是不可或缺,例如:
    public int this [int param]{
    get { return array[param]; }
    set { array[param] = value; }
    }

    static 静态方法 用法:
       通常,在一个类中定义一个方法为static,那就是说,无需本类的对象即可调用此方法。因为this是个引用,哪个对象调用方法就引用哪个对象。 静态方法是属于整个类的,this指的是对当前的对象d的引用。如下所示:
    class Simple{
    static void go(){
    System.out.println(Go...);
    }
    }
    public class Cal{
    public static void main(String[] args){
    Simple.go();
    }
    }
      调用一个静态方法就是“类名.方法名”,静态方法的使用很简单如上所示。一般来说,静态方法常常为应用程序中的其它类提供一些实用工具所用,在Java的类库中大量的静态方法正是出于此目的而定义的。

  • 相关阅读:
    Java System.getProperty vs System.getenv
    Bring JavaScript to your Java enterprise with Vert.x
    es4x 引用外部jar 包以及集成typescrip
    cube.js 最近的一些更新
    es4x 调用其他三方jar 包
    graalvm native image 试用
    es4x 使用nodejs 开发vertx 应用框架试用
    clojure 环境搭建
    restql 学习三 查询语言简单说明
    restql 学习二 几种查询模式
  • 原文地址:https://www.cnblogs.com/sun-frederick/p/4772513.html
Copyright © 2011-2022 走看看