#include <iostream>
using namespace std;
class Rectangle{
private:
double width,height;
public:
Rectangle();
Rectangle(double x, double y);
double getArea(double width,double height);
double getPerimeter(double width,double height);
void setWidth(double width){
this->width = width;
}
void setHeight(double height){
this->height = height;
}
double getWidth(){
return width;
}
double getHeight(){
return height;
}
};
Rectangle::Rectangle():width(1.0),height(1.0){};
Rectangle::Rectangle(double width,double height){
this->width = width;
this->height = height;
}
double getArea(double width,double height){
double Area;
Area = width*height;
return Area;
}
double getPerimeter(double width,double height){
double Perimeter;
Perimeter = (width + height)*2;
}
int main(){
int width,height;
cout<<"请输入宽和高"<<endl;
cin>>width>>height;
Rectangle::getPerimeter(width,height);
return 0;
}
上面那个是我写的程序,一团糟,一地鸡毛。
对照老师的改写了一下,懒猫老师果然厉害~
第一次敲代码敲到十分兴奋!!
#include <iostream>
using namespace std;
class Rectangle{
private:
double width,height;
public:
Rectangle(double width = 1.0, double height = 1.0)
{
this->width = width;
this->height = height;
}
~Rectangle(){}
void setWidth(double width){
this->width = width;
}
void setHeight(double height){
this->height = height;
}
double getWidth(){
return width;
}
double getHeight(){
return height;
}
double getArea(){
return width * height;
}
double getPerimeter(){
return (width + height) * 2;
}
void display(){
cout << "Width = " << getWidth() << " Height = " << getHeight();
cout << " Area = " << getArea() << " Perimeter = " << getPerimeter()<<endl;
}
};
int main(){
double width,height;
Rectangle r1;
cout << "输出第一个缺省的矩形对象的信息:"<<endl;
r1.display();
cout << "请输入矩形的宽度和高度:";
cin >> width >> height;
Rectangle r2(width , height);
cout << "输出第二个缺省的矩形对象的信息:"<<endl;
r2.display();
return 0;
}