声明一个Tree(树)类,有成员ages(树龄),成员函数grow(int years)用以对ages 加上years,showage( )用以显示tree对象的ages值。在主函数中定义Tree类对
时间: 2024-05-22 12:12:59 浏览: 21
象并调用其成员函数。
class Tree:
def __init__(self, ages):
self.ages = ages
def grow(self, years):
self.ages += years
def showage(self):
print("This tree is", self.ages, "years old.")
# 主函数
if __name__ == '__main__':
tree = Tree(10) # 定义Tree类对象
tree.showage() # 显示ages值
tree.grow(5) # 对ages加上5
tree.showage() # 再次显示ages值
相关问题
定义一个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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)