在 C++ 中使用堆内存
Use Heap Memory in c++
我有 3 个 类,形状是我的基础 Class,矩形和三角形是我的衍生 类。
我想将派生的 类 中的四个对象存储到 Shape 的指针。
Shape* sh1=new Shape[4];
Rectangle aR(2,3);
Rectangle bR(4,5);
Triangle aT(2,3);
Triangle bT(4,5);
sh1[0]=&aR;
sh1[1]=&bR;
sh1[2]=&aT;
sh1[3]=&bT;
但我对此有疑问,
我该如何解决?
我能做到
Shape* sh1[4];
Rectangle aR(2,3);
Rectangle bR(4,5);
Triangle aT(2,3);
Triangle bT(4,5);
sh1+0=&aR;
sh1+1=&bR;
sh1+2=&aT;
sh1+3=&bT;
但是为什么我不能做第一种方式?
你的意思是Shape **sh1 = new Shape*[4];
。您需要一个指针数组,而不是一个形状数组。如果您将 Shape
class 抽象化,您也应该得到一个非常有用的诊断。
当然你根本不应该使用new
,而是使用容器:
std::vector<Shape*> sh2 = {&aR, &bR, &aT, &bT};
因为变量 "sh1" 是指向 Shape 的指针,所以 "sh1[0]" 是一个 Shape!
不能将指向 Shape 的指针分配给 Shape。
因此
sh1[0] = &aR
错了。
记住 C/C++
sh1[i] is equal to *(sh+i)
再见
我有 3 个 类,形状是我的基础 Class,矩形和三角形是我的衍生 类。
我想将派生的 类 中的四个对象存储到 Shape 的指针。
Shape* sh1=new Shape[4];
Rectangle aR(2,3);
Rectangle bR(4,5);
Triangle aT(2,3);
Triangle bT(4,5);
sh1[0]=&aR;
sh1[1]=&bR;
sh1[2]=&aT;
sh1[3]=&bT;
但我对此有疑问, 我该如何解决?
我能做到
Shape* sh1[4];
Rectangle aR(2,3);
Rectangle bR(4,5);
Triangle aT(2,3);
Triangle bT(4,5);
sh1+0=&aR;
sh1+1=&bR;
sh1+2=&aT;
sh1+3=&bT;
但是为什么我不能做第一种方式?
你的意思是Shape **sh1 = new Shape*[4];
。您需要一个指针数组,而不是一个形状数组。如果您将 Shape
class 抽象化,您也应该得到一个非常有用的诊断。
当然你根本不应该使用new
,而是使用容器:
std::vector<Shape*> sh2 = {&aR, &bR, &aT, &bT};
因为变量 "sh1" 是指向 Shape 的指针,所以 "sh1[0]" 是一个 Shape!
不能将指向 Shape 的指针分配给 Shape。
因此
sh1[0] = &aR
错了。
记住 C/C++
sh1[i] is equal to *(sh+i)
再见