C++ OJ习题练习(五)定义Tree类

it2023-07-19  71

Problem Description

定义一个Tree(树)类,有成员ages(树龄),成员函数grow(int years)对ages加上years, age()显示Tree对象的ages的值。

下面的程序不完整,请编程完善:

#include <iostream> using namespace std; class Tree{ //你的代码将被嵌在这里 }; int main() { Tree t; t.setages(3); t.age(); t.grow(20); t.age(); return 0; }

Sample Output

3 23

解题代码

#include <iostream> using namespace std; class Tree{ //你的代码将被嵌在这里 int ages; public: void setages(int age){this->ages = age;} void age(){cout << this->ages << endl;}; void grow(int years){this->ages += years;} }; int main() { Tree t; t.setages(3); t.age(); t.grow(20); t.age(); return 0; }
最新回复(0)