1.设计一个名为Rectangle的矩形类,其属性为矩形的长和宽,能计算和输出矩形的周长和面积。
class Rectangle
{
public:Rectangle(int c=0,int k=0):m_c(c),m_k(k){}int length()//周长{return 2 * (m_c + m_k);}int area()//面积{return m_c * m_k;}
private:int m_c;//长int m_k;//宽
};int main()
{Rectangle r1{20,10};cout<<r1.length() << endl;cout << r1.area() << endl;return 0;
}
运行结果:
2.一矩形体育场如下图所示,现在需在其周围建一矩形过道,并在四周围安上栅栏。栅栏价格为50元/米,过道造价为240元/m^2。过道宽为3米,体育场的长宽由键盘输入。请编写程序计算并输出过道和栅栏的造价。
class Stadium //体育场类
{
public:Stadium(int len=1,int w=1):m_x(len), m_y(w){}void show(){cout << "体育场的长:" << m_x << ",宽:" << m_y << endl;cout << " 过道的造价为:" << aisle()<< endl;cout << " 栅栏的造价为:" << fence()<< endl;cout << " 总造价为:" << aisle() + fence() << endl;}int aisle();//过道造价int fence();//栅栏造价
private:int m_x; //长int m_y; //宽
};int Stadium::aisle()//过道造价
{return (m_y * 3 * 2 + (m_x + 3 + 3) * 3 * 2) * 240;
}int Stadium::fence()//栅栏造价
{return 2 * (m_x + m_y) * 50;
}int main()
{cout << "请输入体育场的长和宽:" << endl;int x, y;cin >> x >> y;Stadium s{x,y};s.show();return 0;
}
运行结果:
3.设计一个复数类,要求对其构造函数进行重载。
class Complex //复数类型
{
private:double real;//实部double imag;//虚部
public:Complex():real(0),imag(0)//不带参数的构造函数{}Complex(double r) :real(r), imag(0)//带一个实部参数{}Complex(double r, double i) :real(r), imag(i)//带实部和虚部参数{}void show(){cout << "(" << real << "+" << imag << "i)" << endl;}
};int main()
{Complex c1;c1.show();Complex c2(10);c2.show();Complex c3(1,2);c3.show();return 0;
}