#include <iostream.h> #include <string.h> class CStudent { public: CStudent(char *n, int a); ~CStudent(); static void SetAge(int age); private: char *name; int age; static int nTotalObj; }; int CStudent::nTotalObj = 0; CStudent::CStudent(char *n, int a) :age(a) { int nLen = strlen(n); name = new char[nLen+1]; strcpy(name,n); name[nLen] = '\0'; nTotalObj++; } CStudent::~CStudent() { delete[] name; nTotalObj--; } void CStudent::SetAge(int age) { this->age = age; } void main() { CStudent stu1("张三",25); CStudent str2("李四",26); cout<<"CStudent::nTotalObj="<<CStudent::nTotalObj<<endl; }
时间: 2024-03-31 12:37:27 浏览: 15
这是一个简单的 C++ 程序,定义了一个名为 CStudent 的类,包含了一个构造函数、一个析构函数、一个静态成员变量 nTotalObj 和一个静态成员函数 SetAge。程序的主函数 main 中创建了两个 CStudent 对象 stu1 和 stu2,输出 nTotalObj 的值。这个值表示在程序运行过程中创建的 CStudent 对象的数量。输出结果应该是:CStudent::nTotalObj=2。
相关问题
#include <stdlib.h> #include <iostream.h> #include <fstream.h>
#include <stdlib.h>:这是C/C++标准库中的一个头文件,它包含了一些常用的函数和宏定义,用于处理内存分配、随机数生成、字符串转换等操作。
#include <iostream.h>:这是C++标准库中的一个头文件,它包含了输入输出流的定义和相关操作符的重载,用于进行控制台输入输出。
#include <fstream.h>:这是C++标准库中的一个头文件,它包含了文件输入输出流的定义和相关操作符的重载,用于进行文件的读写操作。
这些头文件在C/C++编程中经常使用,可以帮助我们进行各种输入输出操作和文件处理操作。
范例:
```cpp
#include <stdlib.h>
#include <iostream.h>
#include <fstream.h>
int main() {
// 使用stdlib.h中的函数
int num = rand(); // 生成一个随机数
cout << "Random number: " << num << endl;
// 使用iostream.h中的函数
int input;
cout << "Enter a number: ";
cin >> input;
cout << "You entered: " << input << endl;
// 使用fstream.h中的函数
ofstream file("example.txt"); // 创建一个文件对象
file << "This is an example." << endl; // 写入文件
file.close(); // 关闭文件
return 0;
}
```
#include<stdlib.h> #include<string.h> #include<iostream>
#include 和 #include<> 都是C++的预处理指令,用于引入头文件。其中,#include<> 用于引入标准库的头文件,#include "" 用于引入用户自定义的头文件。所以,对于标准库的头文件,应该使用 #include<iostream>;对于自定义的头文件,应该使用 #include "iostream"。而 #include<stdlib.h> 和 #include<string.h> 是C语言的头文件,C++中应该使用 #include<cstdlib> 和 #include<cstring>。
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.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)
![](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)