例题
对象
#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//不可以这样删除。
// }
储存结构;但指针是在栈里面,而数组在堆里面。栈运行完了会自动释放,但数组要主动释放。不然就找不到堆里面数据了,(没了指针)。
不删除是程序员大忌。(只能循环删除)。