c++例题 构造函数(一)
【项目1拓展(选做)】请自行设计一个矩形类,可以计算矩形的面积、周长、对象线,判断是否是正方形。请用上类似的构造函数,自己设计main()函数,对设计的类进行测试。
[cpp]
#include <iostream>
#include <cmath>
using namespace std;
class Rectangle
{
private:
double length;
double width;
public:
Rectangle():length(1),width(1){}
Rectangle(double len,double wid):length(len),width(wid){}
// Rectangle(double len=1,double wid =1):length(len),width(wid){}
double area(void);
double perimeter(void){ return 2*(length+width); }
double diagonal(void) { return sqrt(length*length+width*width); }
bool square_or_not(void) { return length==width?true:false; }
void show_message(void);
};
//Rectangle::Rectangle(double len,double wid){length = len;width = wid;}
double Rectangle::area(void)
{
return length*width;
}
void Rectangle::show_message(void)
{
cout << "矩形的长宽分别为: " << length << '\t' << width <<endl;
cout << "周长: " << perimeter() << "面积: " << area() << "对角线长度: "<< diagonal() << endl;
cout << "是否为正方形? " << square_or_not() << endl;
}
int main()
{
Rectangle rect1;
rect1.show_message();
Rectangle rect2(3,4);
rect2.show_message();
return 0;
}
#include <iostream>
#include <cmath>
using namespace std;
class Rectangle
{
private:
double length;
double width;
public:
Rectangle():length(1),width(1){}
Rectangle(double len,double wid):length(len),width(wid){}
// Rectangle(double len=1,double wid =1):length(len),width(wid){}
double area(void);
double perimeter(void){ return 2*(length+width); }
double diagonal(void) { return sqrt(length*length+width*width); }
bool square_or_not(void) { return length==width?true:false; }
void show_message(void);
};
//Rectangle::Rectangle(double len,double wid){length = len;width = wid;}
double Rectangle::area(void)
{
return length*width;
}
void Rectangle::show_message(void)
{
cout << "矩形的长宽分别为: " << length << '\t' << width <<endl;
cout << "周长: " << perimeter() << "面积: " << area() << "对角线长度: "<< diagonal() << endl;
cout << "是否为正方形? " << square_or_not() << endl;
}
int main()
{
Rectangle rect1;
rect1.show_message();
Rectangle rect2(3,4);
rect2.show_message();
return 0;
}
补充:软件开发 , C++ ,