一、面向对象
php:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
class
Rectangle
{
private
$width
;
private
$height
;
private
$color
;
public
function
__construct(
$width
,
$height
,
$color
)
{
$this
->width =
$width
;
$this
->height =
$height
;
$this
->color =
$color
;
}
public
function
setColor(
$color
)
{
$this
->color =
$color
;
}
public
function
getColor()
{
return
$this
->color;
}
public
function
area()
{
return
$this
->width *
$this
->height;
}
}
$r1
=
new
Rectangle(12, 2,
"白色"
);
$r2
=
new
Rectangle(9, 4,
"蓝色"
);
echo
"Area of r1 is "
.
$r1
->area().
"\n"
;
echo
"Area of r2 is "
.
$r2
->area().
"\n"
;
echo
"Color of r2 is "
.
$r2
->getColor().
"\n"
;
echo
"set new color\n"
;
$r2
->setColor(
"绿色"
);
echo
"Color of r2 is "
.
$r2
->getColor().
"\n"
;
|
go:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
package main
import
"fmt"
type Rectangle struct {
width, height float64
color string
}
// 如果声明接收者为指定,当使用T类型来调用时,go会自动转换为*T,太TM聪明了
func (r *Rectangle) SetColor(color string) {
r.color = color
}
func (r Rectangle) area() float64 {
return
r.width * r.height
}
func main() {
r1 := Rectangle{12, 2,
"白色"
}
r2 := Rectangle{9, 4,
"蓝色"
}
fmt.Println(
"Area of r1 is: "
, r1.area())
fmt.Println(
"Area of r2 is: "
, r2.area())
fmt.Println(
"Color of r2 is: "
, r2.color)
fmt.Println(
"set new color"
)
r2.SetColor(
"绿色"
)
// 等价于(&r2).SetColor("绿色"),这里r2不需要传地址,当然,传地址也不错,只是go会自动帮助转换,没有必要
fmt.Println(
"Color of r2 is: "
, r2.color)
}
|
本文转自 ustb80 51CTO博客,原文链接:http://blog.51cto.com/ustb80/1604795,如需转载请自行联系原作者