声明一个Tree(树)类,有成员ages(树龄),成员函数grow(int years)用以对ages 加上years,showage( )用以显示tree对象的ages值。在主函数中定义Tree类对
时间: 2024-05-14 15:14:26 浏览: 16
象并测试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
```
相关问题
定义一个Tree(树)类,有成员ages(树龄),成员函数grow(int years)对ages加上years,age()显示tree对象的ages的值。
好的,这是一个编程问题,我可以回答。以下是Tree类的定义:
```
class Tree {
private:
int ages; // 树龄
public:
Tree(int a) : ages(a) {} // 构造函数,初始化树龄
void grow(int years) { ages += years; } // 成长函数,增加树龄
int age() { return ages; } // 显示树龄
};
```
使用示例:
```
Tree myTree(10); // 创建一个树龄为10的树对象
myTree.grow(5); // 让树增加5年
cout << "My tree is " << myTree.age() << " years old." << endl; // 显示树龄
```
输出结果为:
```
My tree is 15 years old.
```
用C++定义一个Tree(树)类,有成员ages(树龄),成员函数grow(int years)对ages加上years,ages()显示tree对象的ages的值。
好的,这是一个简单的Tree类的定义:
```c++
class Tree {
private:
int ages;
public:
Tree(int ages = 0) : ages(ages) {}
void grow(int years) {
ages += years;
}
int getAges() const {
return ages;
}
};
```
使用方法:
```c++
Tree tree(10);
tree.grow(5);
cout << "The ages of the tree is: " << tree.getAges() << endl;
```
输出结果:
```
The ages of the tree is: 15
```
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![html](https://img-home.csdnimg.cn/images/20210720083451.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)