指向整数数组的指针的初始化 我在C++中有以下疑问。 我们知道,我们可以在声明时初始化指针,如下所示: int *p = new int(8) cout<<*p<<endl; int main() { int *p = new int[10]{1,2,3,4,5,6,7,8,9,10}; cout << p[7] << endl; return 0; }
这可以初始化为:指向整数数组的指针的初始化 我在C++中有以下疑问。 我们知道,我们可以在声明时初始化指针,如下所示: int *p = new int(8) cout<<*p<<endl; int main() { int *p = new int[10]{1,2,3,4,5,6,7,8,9,10}; cout << p[7] << endl; return 0; },c++,C++,这可以初始化为: p[0] = 7 p[1] = 9; 但是有什么方法可以在声明时进行初始化吗?使用c++11可以使用大括号初始化: int *p = new int[10] { 7, 9 }; // And so on for additional values past the first 2 elements 使用c++11可以使用大括号初始化: int *p = new int[10] { 7, 9 }; // And so on for additional values pa
p[0] = 7
p[1] = 9;
但是有什么方法可以在声明时进行初始化吗?使用c++11可以使用大括号初始化:
int *p = new int[10] { 7, 9 }; // And so on for additional values past the first 2 elements
使用c++11可以使用大括号初始化:
int *p = new int[10] { 7, 9 }; // And so on for additional values past the first 2 elements
是的,例如,如果要将数组初始化为1,2,3,4,可以编写:
int[]myarray={1,2,3,4}是的,例如,如果要将数组初始化为1,2,3,4,您可以编写:
int[]myarray={1,2,3,4}是的,你可以这样做
int *p = new int[3] {4,5,6};
是的,你可以这样做
int *p = new int[3] {4,5,6};
Yo可以按如下方式使用“{}”:
int *p = new int(8)
cout<<*p<<endl;
int main()
{
int *p = new int[10]{1,2,3,4,5,6,7,8,9,10};
cout << p[7] << endl;
return 0;
}
intmain()
{
int*p=新的int[10]{1,2,3,4,5,6,7,8,9,10};
coutYo可以按如下方式使用“{}”:
int *p = new int(8)
cout<<*p<<endl;
int main()
{
int *p = new int[10]{1,2,3,4,5,6,7,8,9,10};
cout << p[7] << endl;
return 0;
}
intmain()
{
int*p=新的int[10]{1,2,3,4,5,6,7,8,9,10};
cout正如其他人所说,您可以使用C++11列表初始化{}
或者您可以重载new[]
并使用数组进行初始化,如下所示:
#include <iostream>
void* operator new[](std::size_t sz, int *arr)
{
void* p = operator new[](sz);
int *ptr= (int *)p;
std::size_t i=0;
for(;i<sz;++i)
ptr[i] = arr[i];
return p;
}
int main()
{
int arr[] ={1,2,3,4,5,6,7,8};
int* p = new( arr) int[8];
for(int i=0;i<8;i++)
std::cout<<p[i] << std::endl;
delete[] p;
}
#包括
void*运算符new[](标准::size_t sz,int*arr)
{
void*p=运算符new[](sz);
int*ptr=(int*)p;
标准:尺寸i=0;
对于(;i正如其他人所说,您可以使用C++11列表初始化{}
或者您可以重载new[]
并使用数组进行初始化,如下所示:
#include <iostream>
void* operator new[](std::size_t sz, int *arr)
{
void* p = operator new[](sz);
int *ptr= (int *)p;
std::size_t i=0;
for(;i<sz;++i)
ptr[i] = arr[i];
return p;
}
int main()
{
int arr[] ={1,2,3,4,5,6,7,8};
int* p = new( arr) int[8];
for(int i=0;i<8;i++)
std::cout<<p[i] << std::endl;
delete[] p;
}
#包括
void*运算符new[](标准::size_t sz,int*arr)
{
void*p=运算符new[](sz);
int*ptr=(int*)p;
标准:尺寸i=0;
对于(;它很好,除非像这里一样,您想用new
分配数组。除非像这里一样,您想用new
分配数组,否则它很好。