Defining struct Types
Inspect one language lane at a time so line-level text and code deltas stay readable.
Diff Lane
English
0 modified sections0 code block delta0 anchor delta
Diff Lane
中文
1 modified sections0 code block delta0 anchor delta
modifiedstruct 成员的访问修饰符text+1 line, -1 line
v1.0.5
Section Text
1
`struct` 的成员(包括成员变量、成员属性、构造函数、成员函数、操作符函数(详见[操作符重载](../function/operator_overloading.md)章节))用 4 种访问修饰符修饰:`private`、`internal`、`protected` 和 `public`,缺省的修饰符是 `internal`。2
3
- `private` 表示在 `struct` 定义内可见。4
- `internal` 表示仅当前包及子包(包括子包的子包,详见[包](../package/toplevel_access.md)章节)内可见。5
- `protected` 表示当前模块(详见[包](../package/toplevel_access.md)章节)可见。6
- `public` 表示模块内外均可见。7
8
下面的例子中,`width` 是 `public` 修饰的成员,在类外可以访问,`height` 是缺省访问修饰符的成员,仅在当前包及子包可见,其他包无法访问。9
10
<!-- compile.error -->11
12
13
<!-- compile.error -->14
<!-- cfg="-p b --output-type=staticlib" -->15
<!-- cfg="liba.a" -->Code 1 · cangjie
1
package a2
public struct Rectangle {3
public var width: Int644
var height: Int645
private var area: Int646
7
public init(width: Int64, height: Int64, area: Int64) {8
this.width = width9
this.height = height10
this.area = area11
}12
}13
14
func samePkgFunc() {15
var r = Rectangle(10, 20, 40)16
r.width = 8 // OK: public 'width' can be accessed here17
r.height = 24 // OK: 'height' has no modifier and can be accessed here18
r.area = 30 // Error, private 'area' can't be accessed here19
}Code 2 · cangjie
1
package b2
import a.*3
4
main() {5
r.width = 8 // OK: public 'width' can be accessed here6
r.height = 24 // Error, no modifier 'height' can't be accessed here7
r.area = 30 // Error, private 'area' can't be accessed here8
}v1.1.0
Section Text
1
`struct` 的成员包括成员变量、成员属性、构造函数、成员函数、操作符函数(详见[操作符重载](../function/operator_overloading.md)),这些成员可使用四种访问修饰符:`private`、`internal`、`protected` 和 `public`,缺省的修饰符是 `internal`。2
3
- `private` 表示在 `struct` 定义内可见。4
- `internal` 表示仅当前包及子包(包括子包的子包,详见[包](../package/toplevel_access.md)章节)内可见。5
- `protected` 表示当前模块(详见[包](../package/toplevel_access.md)章节)可见。6
- `public` 表示模块内外均可见。7
8
下面的例子中,`width` 是 `public` 修饰的成员,在类外可以访问,`height` 是缺省访问修饰符的成员,仅在当前包及子包可见,其他包无法访问。9
10
<!-- compile.error -->11
12
13
<!-- compile.error -->14
<!-- cfg="-p b --output-type=staticlib" -->15
<!-- cfg="liba.a" -->Code 1 · cangjie
1
package a2
public struct Rectangle {3
public var width: Int644
var height: Int645
private var area: Int646
7
public init(width: Int64, height: Int64, area: Int64) {8
this.width = width9
this.height = height10
this.area = area11
}12
}13
14
func samePkgFunc() {15
var r = Rectangle(10, 20, 40)16
r.width = 8 // OK: public 'width' can be accessed here17
r.height = 24 // OK: 'height' has no modifier and can be accessed here18
r.area = 30 // Error, private 'area' can't be accessed here19
}Code 2 · cangjie
1
package b2
import a.*3
4
main() {5
r.width = 8 // OK: public 'width' can be accessed here6
r.height = 24 // Error, no modifier 'height' can't be accessed here7
r.area = 30 // Error, private 'area' can't be accessed here8
}