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
}
相关推荐
_waylau7 天前
首本鸿蒙架构师培养手册《鸿蒙架构师修炼之道》简介
华为·harmonyos·鸿蒙·鸿蒙系统·仓颉·cangjie
星空下的月光影子1 个月前
text_encoding4cj 仓颉三方库实战教程
文件处理·仓颉
长弓三石1 个月前
鸿蒙网络编程系列60-仓颉版TLS客户端示例
网络·harmonyos·鸿蒙·仓颉
superman超哥1 个月前
仓颉并发调试利器:数据竞争检测的原理与实战
开发语言·仓颉编程语言·仓颉
superman超哥1 个月前
仓颉元编程进阶:编译期计算能力的原理与深度实践
开发语言·后端·仓颉编程语言·仓颉·仓颉语言·仓颉元编程·编译器计算能力
superman超哥1 个月前
仓颉跨语言编程:FFI外部函数接口的原理与深度实践
开发语言·后端·仓颉编程语言·仓颉·仓颉语言·仓颉跨语言编程·ffi外部函数接口
superman超哥1 个月前
仓颉动态特性探索:反射API的原理、实战与性能权衡
开发语言·后端·仓颉编程语言·仓颉·仓颉语言·仓颉动态特性·反射api
superman超哥1 个月前
仓颉元编程之魂:宏系统的设计哲学与深度实践
开发语言·后端·仓颉编程语言·仓颉·仓颉语言·仓颉语言特性
superman超哥1 个月前
仓颉设计哲学核心:零成本抽象的实现原理与深度实践
开发语言·仓颉编程语言·仓颉·零成本抽象·仓颉设计
superman超哥1 个月前
仓颉并发编程核心:线程安全保证的原理与实践
仓颉编程语言·仓颉