golang的面向对象
时间:2024-1-19 22:57 作者:xiang 分类: 无
php 代码
<?php
class Cat {
private $age;
private $color;
public function __construct($age, $color) {
$this->age = $age;
$this->color = $color;
}
public function getAge() {
return $this->age;
}
public function getColor() {
return $this->color;
}
public function eat() {
echo "Cat is eating.\n";
}
public function sleep() {
echo "Cat is sleeping.\n";
}
}
$myCat = new Cat(3, 'brown');
echo "Age: " . $myCat->getAge() . "\n";
echo "Color: " . $myCat->getColor() . "\n";
$myCat->eat();
$myCat->sleep();
?>
golang
package main
import "fmt"
// Cat ç»æä½
type Cat struct {
age int
color string
}
func NewCat(age int, color string) *Cat {
return &Cat{age, color}
}
func (c *Cat) GetAge() int {
return c.age
}
func (c *Cat) GetColor() string {
return c.color
}
func (c *Cat) Eat() {
fmt.Println("Cat is eating.")
}
func (c *Cat) Sleep() {
fmt.Println("Cat is sleeping.")
}
func main() {
myCat := NewCat(3, "brown")
fmt.Println("Age:", myCat.GetAge())
fmt.Println("Color:", myCat.GetColor())
myCat.Eat()
myCat.Sleep()
}