#include <iostream> using namespace std; class Tree { public: Tree();//构造函数 void grow(int years);//对数龄ages加上years void age();//显示数龄ages的值 private: int ages;//树龄 }; int main() { Tree tree; int years; cin >> years; tree.grow(years); tree.age(); return 0; } Tree::Tree(){ ages=1; } void Tree:: grow(int years){ ages+=years; } void Tree::age(){ cout<<ages; }
时间: 2024-03-29 12:41:45 浏览: 19
这段代码实现了一个树(Tree)类,该类包含三个成员函数:构造函数(Tree)、grow()和age(),以及一个私有成员变量ages,表示树的年龄。
在主函数中,首先创建了一个树的对象tree,然后通过cin输入一个整数years,表示需要将树的年龄增加years年。接着,调用tree对象的grow()函数,将years作为参数传递给该函数,使树的年龄增加years年。最后,调用tree对象的age()函数,输出树的当前年龄ages的值。
在Tree类中,构造函数Tree()使用初始化列表将私有成员变量ages初始化为1。grow()函数将传入的参数years加到ages上,age()函数用于输出当前年龄ages的值。
相关问题
#include<iostream> #include<cstdio> using namespace std;是什么意思
#include<iostream> #include<cstdio> using namespace std; 是C++中的预处理指令,用于引入头文件和命名空间。
1. #include<iostream> 是引入iostream头文件,其中包含了输入输出流的定义,例如cout和cin等。
2. #include<cstdio> 是引入cstdio头文件,其中包含了C语言标准输入输出函数的定义,例如printf和scanf等。
3. using namespace std; 是使用std命名空间,std是C++标准库的命名空间,其中包含了很多常用的函数和类。
这些预处理指令的作用是为了在程序中能够使用输入输出流和标准库函数,使得程序更加方便和简洁。
补全程序,并写出程序运行结果。 #include <iostream> using namespace std; class Class { public : Class ( int...
补全程序如下:
```
#include <iostream>
using namespace std;
class Class {
public:
Class(int num) {
cout << "Constructor with one argument called." << endl;
}
Class(int num1, int num2) {
cout << "Constructor with two arguments called." << endl;
}
};
int main() {
Class obj1(10);
Class obj2(20, 30);
return 0;
}
```
程序运行结果为:
```
Constructor with one argument called.
Constructor with two arguments called.
```
解释:
这是一个带有两个构造函数的类`Class`。第一个构造函数接受一个整数参数,第二个构造函数接受两个整数参数。在`main`函数中,我们创建了两个对象`obj1`和`obj2`,分别调用了两个不同的构造函数。所以,程序输出了两个不同的消息。