面向对象C++习题解答

.

4-8 定义一个Dog类,包含age,weight等属性,以及对这些属性操作的方法。实现并测试这个类。

#include using namespace std; class Dog {

public:

void setAge(int a) {

age=a; }

int getAge() {

return age; }

void setWeight(float w) {

weight=w; }

float getWeight() {

return weight; } private: int age;

float weight; };

void main() {

Dog d;

d.setAge(3); d.setWeight(30);

cout<<\小狗:\岁,重\斤。\}

4-9 设计并测试一个名为Rectangle的矩形类,其属性为矩形的左下角与右上角两个点的坐标,根据坐标能计算矩形的面积。

#include #include using namespace std; class Rectangle

.

.

{

public:

Rectangle(int xx1,int yy1,int xx2,int yy2) {

x1=xx1; y1=yy1; x2=xx2; y2=yy2; }

float getArea() {

return fabs(x2-x1)*fabs(y2-y1); } private:

int x1,y1; int x2,y2; };

void main() {

Rectangle rec(0,0,10,20);

cout<<\矩形面积:\}

4-11 定义并实现一个矩形类,有长、宽两个属性,由成员函数计算矩形的面积。

#include using namespace std; class Rectangle {

public:

Rectangle(int l,int w) {

length=l; width=w; }

float getArea() {

return length*width; } private:

int length; int width; };

.

.

void main() {

Rectangle rec(10,20);

cout<<\矩形面积:\}

4-13 定义一个Circle类,有数据成员radius(半径),成员函数getArea(),计算圆的面积,构造一个Circle的对象进行测试。

#include using namespace std; const float PI=3.1415; class Circle {

public:

Circle(float r) {

radius=r; }

float getArea() {

return radius*PI*PI; } private:

float radius; };

void main() {

Circle c(5.5);

cout<<\圆的面积:\}

4-20 定义一个复数类Complex,使得下面的代码能够工作。

Complex c1(3,5); Complex c2=4.5; c1.add(c2); c1.show() ;

.

联系客服:779662525#qq.com(#替换为@) 苏ICP备20003344号-4