指向对象的指针数组

例题

 

对象

#include <iostream>
using  namespace std;                    //必备
class Rectangle
{
private:                                 //私有的
	double width;
	double height;
    static int count;
public:                                  //共有的
	~Rectangle()                                    //析构函数
    {
        count--;
        cout << "自动调用析构函数" << endl;
    };
    //Rectangle(double width = 1.0, double height = 1.0)//有参构造函数:作用传值。
    //{
    //    this->width = width;
    //    this->height = height;
    //    count++;
    //    cout <<endl<< "调用有参构造函数"<<endl;
    //}
    //Rectangle()           //不需要参数传入。                 //无参构造函数
    {
        width = height = 1;
        
        cout << endl << "自动调用无参构造函数" << endl;
        count++;
    }
    void setwidth(int wdith)              
    {
        this->width = width;
    }

    void setheight(int height) {

        this->height = height;

    }

    //获得属性的值

    double getwidth() {

        return width;

    }

    double getheight() {

        return height;

    }
    double getarea()
{
    return   width * height;
}
    double getperimeter()
{
    return (width + height) * 2;
} static double getCount()
    {
        return count;
    }
    void display()//二次调用。
    {
        cout << "width=" << getwidth()<< "height=" << getheight()<<endl;
        cout << "area" << getarea() << "perimeters" << getperimeter();
        cout << "矩形对象为" << Rectangle::getCount() << endl << endl;
    }
};

 

 1    缺点:会创建3个野指针。

r的声明在for循环里面

  const int n = 3;
    Rectangle* pRectangle[n];//指向对象的指针数组方法1
    int w, h;
    for (int i = 0; i < n; i++)
    {
        cout << "请输入第" << i << "个矩形的宽度和高度";
        cin >> w >> h;
        Rectangle r(w, h);//
        pRectangle[i] = &r;
        pRectangle[i]->display();
    }

储存模式

 

 

 最后

 

 

 

2(能实现多态)

 

  const int n = 3;
 //   Rectangle* pRectangle[n];//存放在栈里面,静态。
 //   int w, h;
 //   for (int i = 0; i < n; i++)
 //   {
 //       cout << "请输入第" << i << "个矩形的宽度和高度";
 //       cin >> w >> h;
 //       pRectangle[i] = new Rectangle(w, h);
 //       pRectangle[i]->display();

 //   }
 //   for (int i = 0; i < n; i++)
 //   {
 //       delete pRectangle[i];
 //delete[]rect//不可以这样删除。
 //   }

 

 储存结构;但指针是在栈里面,而数组在堆里面。栈运行完了会自动释放,但数组要主动释放。不然就找不到堆里面数据了,(没了指针)。

 

 

 不删除是程序员大忌。(只能循环删除)。

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值