Dart 运算符重载,详细介绍

简介: Dart 运算符重载,详细介绍Dart 支持运算符重载,它允许我们重载内置的运算符以执行自定义操作。在 Dart 中,我们可以通过实现一些特定的方法来重载运算符。

Dart 运算符重载,详细介绍

Dart 支持运算符重载,它允许我们重载内置的运算符以执行自定义操作。在 Dart 中,我们可以通过实现一些特定的方法来重载运算符。

下面是一些常用的运算符和它们对应的 Dart 方法:


+ : operator +(Object other)

`` : operator -(Object other)

`` : operator *(Object other)

/ : operator /(Object other)

% : operator %(Object other)

< : operator <(Object other)

> : operator >(Object other)

<= : operator <=(Object other)

>= : operator >=(Object other)

== : operator ==(Object other)

[] : operator [](index)

[]= : operator []=(index, value)

~ : operator ~()

| : operator |(Object other)

& : operator &(Object other)

^ : operator ^(Object other)

<< : operator <<(Object other)

>> : operator >>(Object other)

注意事项:


运算符重载方法必须是实例方法(instance method)。

重载方法必须是公有的(public)。

某些运算符是不能被重载的,例如 ?. 和 ..。


通过重载运算符,我们可以使我们的自定义类更加灵活和易于使用。例如,我们可以定义一个名为 Vector 的类来表示二维向量,然后重载 + 运算符,以便我们可以轻松地对两个向量执行向量加法操作。

class Vector {
  int x, y;
  Vector(this.x, this.y);
  Vector operator +(Vector other) {
    return Vector(x + other.x, y + other.y);
  }
}
void main() {
  Vector v1 = Vector(2, 3);
  Vector v2 = Vector(4, 5);
  Vector result = v1 + v2;
  print(result.x); // 输出:6
  print(result.y); // 输出:8
}

以上是 Dart 运算符重载的简要介绍,希望能对你有所帮助!

相关文章
|
4天前
|
Kotlin
Kotlin中的函数定义
Kotlin中的函数定义
10 4
|
6天前
|
Dart
Dart之类型转换
Dart之类型转换
5 0
|
6天前
|
安全 开发者 Kotlin
Kotlin变量
Kotlin变量
4 0
|
6天前
|
Kotlin
Kotlin函数
Kotlin函数
7 0
|
9月前
|
JavaScript
TypeScript-继承和函数、函数声明和重载
TypeScript-继承和函数、函数声明和重载
43 0
TypeScript-继承和函数、函数声明和重载
|
Dart Java 索引
那些你不知道的Dart细节之内置类型(二)
在Dart中,内置类型有以下几种:Numbers 数值、Strings 字符串、Booleans 布尔值、Lists 列表(数组)、Sets 集合、Maps 集合、Runes 符号字符、Symbols 标识符。
136 0
|
Dart
Dart之 初始化列表
Dart之 初始化列表
41 0
Dart之 初始化列表
|
Dart
Dart之运算符
Dart之运算符
41 0
Dart之运算符
|
Dart
Dart 之 操作符
Dart 之 操作符
54 0
Dart 之 操作符