声明一个Tree(树)类,有成员ages(树龄),成员函数grow(int years)用以对ages 加上years,showage( )用以显示tree对象的ages值。在主函数中定义Tree类对
时间: 2024-05-14 11:14:26 浏览: 65
象并测试grow和showage函数。
```python
class Tree:
def __init__(self, ages):
self.ages = ages
def grow(self, years):
self.ages += years
def showage(self):
print("Tree age is", self.ages)
if __name__ == '__main__':
tree = Tree(10)
tree.showage()
tree.grow(5)
tree.showage()
```
输出:
```
Tree age is 10
Tree age is 15
```
相关问题
使用C++编写一个声明一个Tree(树)类,有成员ages(树龄),成员函数grow(int years)用以对ages 加上years,showage( )用以显示tree对象的ages值。在主函数中定义Tree类对
#include <stdio.h>
class Tree {
private:
int ages;
public:
Tree(int a) {
ages = a;
}
void grow(int years) {
ages += years;
}
void showage() {
printf("The age of the tree is %d years old.\n", ages);
}
};
int main() {
Tree tree(10);
tree.showage();
tree.grow(5);
tree.showage();
return 0;
}
声明一个Tree(树)类,有成员ages(树龄), 定义构造函数,成员函数grow(int years)用以对ages 加上years,showage( )用以显示tree对象的ages值。在主函数中定义Tree类对象并输出其树龄
好的,下面是代码实现:
```python
class Tree:
def __init__(self, ages):
self.ages = ages
def grow(self, years):
self.ages += years
def showage(self):
print("树龄为:", self.ages)
# 主函数
tree = Tree(10)
tree.showage()
tree.grow(5)
tree.showage()
```
输出结果为:
```
树龄为: 10
树龄为: 15
```
其中,tree对象的树龄初始值为10,grow函数将其增加了5,最后输出结果为15。
阅读全文