簡體   English   中英

Dart - 使用超級調用命名構造函數與 class 名稱

[英]Dart - Call Named Constructor using super vs class name

class Person {
  late String name;
  late int age;
  Person();
  Person.ap(this.name, this.age);
}

class Employee extends Person {
  Employee(String name, int age) : super.ap(name, age); // This works

  // This is giving error. The method 'ap' isn't defined in a superclass of 'Employee'.
  Employee(String name, int age) {
    super.ap(name, age);
  }
}

使用 super 或在括號內調用未命名的構造函數有什么區別?

您正在制作兩個同名的構造函數。 做這樣的事情

class Employee extends Person {

Employee(String name, int age) : super.ap(name, age);

Employee.foo(String name, int age): super.ap(name, age);

}

試試這個,只需在Person class中創建一個名為ap的 setter function


     class Person {
          late String name;
          late int age;
          Person();
          Person.ap(this.name, this.age);
          
          ap(String name, int age){ //add this           
              this.name=name;
              this.age=age;
            }
        }
        
        class Employee extends Person {

          //here ap is name constructor 
          Employee(String name, int age) : super.ap(name, age);
          
          //here ap is setter function in the person class
          Employee.ap(String name, int age) {
            super.ap(name, age);
          }
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM