28-创建 struct 实例

28-创建 struct 实例

定义了 struct 类型后,即可通过调用 struct 的构造函数来创建 struct 实例。在 struct 定义之外,通过 struct 类型

名调用构造函数。例如,下例中定义了一个 Rectangle 类型的变量 r

javascript 复制代码
let r = Rectangle(10, 20)

创建了 struct 实例之后,可以通过实例访问它的(public 修饰的)实例成员变量和实例成员函数。例如,下例中通过 r.wid

thr.height 可分别访问 rwidthheight 的值,通过 r.area() 可以调用 r 的成员函数 area

javascript 复制代码
let r = Rectangle(10, 20)
let width = r.width   // width = 10
let height = r.height // height = 20
let a = r.area()      // a = 200

如果希望通过 struct 实例去修改成员变量的值,需要将 struct 类型的变量定义为可变变量,并且被修改的成员变量也必须是

可变成员变量(使用 var 定义)。举例如下:

javascript 复制代码
struct Rectangle {
    public var width: Int64
    public var height: Int64

    public init(width: Int64, height: Int64) {
        this.width = width
        this.height = height
    }

    public func area() {
        width * height
    }
}

main() {
    var r = Rectangle(10, 20) // r.width = 10, r.height = 20
    r.width = 8               // r.width = 8
    r.height = 24             // r.height = 24
    let a = r.area()          // a = 192
}

在赋值或传参时,会对 struct 实例进行复制,生成新的实例,对其中一个实例的修改并不会影响另外一个实例。以赋值为

例,下面的例子中,将 r1 赋值给 r2 之后,修改 r1widthheight 的值,并不会影响 r2widthheight 值。

javascript 复制代码
struct Rectangle {
    public var width: Int64
    public var height: Int64

    public init(width: Int64, height: Int64) {
        this.width = width
        this.height = height
    }

    public func area() {
        width * height
    }
}

main() {
    var r1 = Rectangle(10, 20) // r1.width = 10, r1.height = 20
    var r2 = r1                // r2.width = 10, r2.height = 20
    r1.width = 8               // r1.width = 8
    r1.height = 24             // r1.height = 24
    let a1 = r1.area()         // a1 = 192
    let a2 = r2.area()         // a2 = 200
}
相关推荐
We....9 天前
仓颉函数:定义、调用与进阶特性
函数·仓颉
We....12 天前
仓颉语言入门:核心概念与基础数据类型
编程语言·仓颉·仓颉鸿蒙
_waylau16 天前
跟老卫学仓颉编程语言开发:浮点类型
人工智能·华为·harmonyos·鸿蒙·鸿蒙系统·仓颉
坚果的博客19 天前
cjman:仓颉生态的轻量化工程管理工具
仓颉
_waylau23 天前
跟老卫学仓颉编程语言开发:整数类型
算法·华为·harmonyos·鸿蒙·鸿蒙系统·仓颉
_waylau1 个月前
首本鸿蒙架构师培养手册《鸿蒙架构师修炼之道》简介
华为·harmonyos·鸿蒙·鸿蒙系统·仓颉·cangjie
星空下的月光影子2 个月前
text_encoding4cj 仓颉三方库实战教程
文件处理·仓颉
长弓三石2 个月前
鸿蒙网络编程系列60-仓颉版TLS客户端示例
网络·harmonyos·鸿蒙·仓颉
superman超哥2 个月前
仓颉并发调试利器:数据竞争检测的原理与实战
开发语言·仓颉编程语言·仓颉
superman超哥2 个月前
仓颉元编程进阶:编译期计算能力的原理与深度实践
开发语言·后端·仓颉编程语言·仓颉·仓颉语言·仓颉元编程·编译器计算能力