c++对象数组的3种方式

 题目

 

1.对象

#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

int mian(){  
 const int n = 3;
    Rectangle rect[n] = { Rectangle(3,4),Rectangle(7,4),Rectangle(4,9) };//调用有参构造函数。
   // Rectangle rect[n];//当类 "Rectangle" 包含多个默认构造函数,故要把当中其中应该构造函数屏蔽掉,
    //当运行到这一步时数据已经被放入盒子中了。接下来就是输出。
    for (int i = 0; i < n; i++)
    {
        rect[i].display();

    }
    return 0;
 }

 相当于把数据入盒子中了(栈)。接下来就是输出。

 

 

 静态2。

记得对构造函数进行解除//

存储机制跟上面一样。

 

int main()
{ 
 //对象的创建与消亡都是系统自动完成的。
    const int n = 3;
    //Rectangle rect[n] = { Rectangle(3,4),Rectangle(7,4),Rectangle(4,9) };//调用有参构造函数。
   Rectangle rect[n];//当类 "Rectangle" 包含多个默认构造函数,故要把当中其中应该构造函数屏蔽掉,
    //当运行到这一步时数据已经被放入盒子中了。接下来就是输出。
    for (int i = 0; i < n; i++)
    {
        rect[i].display();

    }
    return 0;
 }

3.动态3

与上面的区别是这里放在堆里面。储存结构同上。

r生命周期在for的括号末。

int main()
{
    int num;
    cout << "请输入要建立的数组对像个数";
    cin >> num;
    Rectangle* rect = new Rectangle[num];//放到堆里面。//指针数组。
    rect[0].setwidth(3.0);
    rect[0].setheight(4.0);
    for (int i = 0; i < num; i++)
    {
        rect[i].display();
    }
    delete[]rect;//动态才可以这样删除。

 小结:静态数组系统自动释放。动态数组用delete释放。

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值