#include<iostream> using namespace std; template<typename T> class Myarr { T * date; int size; public: Myarr() { date = NULL; size = 0; } ~Myarr() { if (date != NULL) { delete[] date; } } void add(T Add) { T * AddedArr = new T[size+1]; for (int i = 0; i < size; i++) { AddedArr[i] = date[i]; } AddedArr[size] = Add; delete[] date; date = AddedArr; this->size++; } void getArr(int i) { for (int i = 0; i < this->size; i++) cout<< date[i]<<endl; } int getsize() { return this->size; } }; int main() { int i=0; char ch; Myarr<int> arr; cin >> i; for (i = 0; i < 100; i++) { int j = 0; cin >> j; arr.add(j); if ((ch=getchar())=='\n') break; } arr.getArr(arr.getsize()); system("pause");c++重载<<
时间: 2024-03-20 09:44:36 浏览: 20
这段代码实现了一个可变长数组类 Myarr,可以通过 add 函数往数组中添加元素,通过 getArr 函数输出数组中的元素。其中使用了模板类,可以存储不同类型的数据。另外,使用了动态内存分配,可以根据需要动态增加数组的大小。该程序最后输出了添加的所有元素。
对于重载 << 运算符,需要在 Myarr 类中添加友元函数:
```
template<typename T>
class Myarr {
...
friend ostream& operator<<(ostream& os, const Myarr<T>& arr) {
for (int i = 0; i < arr.size; i++) {
os << arr.date[i] << " ";
}
return os;
}
};
```
这样就可以通过 cout << arr 的方式输出整个数组了。
相关问题
#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;
这是一个C++的代码片段,它包含了iostream头文件和使用了命名空间std。iostream头文件提供了输入输出流的功能,而using namespace std;语句则是为了方便使用std命名空间中的函数和对象,避免每次都需要写std::。
以下是一个简单的示例代码,展示了如何使用iostream头文件和命名空间std来输出一句话:
```cpp
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl;
return 0;
}
```
这段代码会输出"Hello, World!",endl是一个特殊的控制符,用于在输出流中插入一个换行符。