类指针可以用来指向类的地址,也可以指向动态内存分配的类,注意,动态初始化的类需要进行释放。
#include <iostream>
using namespace std;
class Rectangle{
int height,width;
public:
Rectangle(int h,int w):height(h),width(w){
}
int area(){
return height * width;
}
};
int main(void)
{
Rectangle obj(3,4);
Rectangle *p1,*p2,*p3;
p1 = &obj;
p2 = new Rectangle(4,6);
p3 = new Rectangle[2]{{1,2},{3,4}};
cout << p1->area() << endl;
cout << p2->area() << endl;
cout << p3[0].area() << " " << p3[1].area() << endl;
delete p2;
delete []p3;
return 0;
}


被折叠的 条评论
为什么被折叠?



