马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 bin554385863 于 2019-11-19 00:21 编辑 #include <iostream>
#include <initializer_list>
template <typename tp>
class carray
{
private:
tp *ARRAY;
size_t LENGTH;
public:
/*********************************************************************/
carray() : ARRAY(nullptr), LENGTH(0) {} //默认构造
/*********************************************************************/
carray(std::initializer_list<tp> list) : LENGTH(list.size()) //普通构造
{
ARRAY = new tp[LENGTH];
for (size_t i = 0; i < LENGTH; i++)
{
ARRAY[i] = *(list.begin() + i);
}
}
/*********************************************************************/
carray(carray<tp> &arr) //复制构造
{
LENGTH = arr.LENGTH;
ARRAY = new tp [LENGTH];
for (size_t i = 0; i < LENGTH; i++)
{
*(ARRAY+i) = arr[i];
}
}
/*********************************************************************/
void pushback(tp data)
{
tp *t_ARRAY = new tp[LENGTH + 1];
for (size_t i = 0; i < LENGTH; i++)
{
t_ARRAY[i] = ARRAY[i];
}
t_ARRAY[LENGTH] = data;
LENGTH += 1;
delete[] ARRAY;
ARRAY = t_ARRAY;
}
/*********************************************************************/
size_t size()
{
return LENGTH;
}
/*********************************************************************/
tp operator[](const size_t i) //重载索引下标符号[]
{
return ARRAY[i];
}
/*********************************************************************/
friend std::ostream &operator<<(std::ostream &os, carray &arr) //重载输出流符号<<
{
for (size_t i = 0; i < arr.size(); i++)
{
os << arr[i];
}
return os;
}
/*********************************************************************/
~carray()
{
delete[] ARRAY;
}
};
// template <typename tp>
// std::ostream &operator<<(std::ostream &os, carray<tp> &arr)
// {
// size_t sz = arr.size();
// for (size_t i = 0; i < sz; i++)
// {
// os << arr[i];
// }
// return os;
// }
int main(int argc, char const *argv[])
{
carray<int> arr = {0};
std::cout << arr << " " << arr.size() << std::endl;
arr.pushback(999);
std::cout << arr << " " << arr.size() << std::endl;
carray<int> t_arr = arr;
std::cout << t_arr << " " << t_arr.size() << std::endl;
return 0;
}
-------------------------------------------------------------------------------------------------------------------------------------
Microsoft Windows [版本 10.0.18363.476]
(c) 2019 Microsoft Corporation。保留所有权利。
E:\Users\admin\Documents\VScode>c:\Users\admin\.vscode\extensions\ms-vscode.cpptools-0.26.1\debugAdapters\bin\WindowsDebugLauncher.exe --stdin=Microsoft-MIEngine-In-3s3sbjmi.ihk --stdout=Microsoft-MIEngine-Out-a4bdh2dw.pub --stderr=Microsoft-MIEngine-Error-y55is3ur.rkh --pid=Microsoft-MIEngine-Pid-kx3esz3t.ch1 --dbgExe=D:\MinGW\bin\gdb.exe --interpreter=mi
0 1
0999 2
0999 2
E:\Users\admin\Documents\VScode>
----------------------------------------------------------------------------------------------------------
|