编写程序: 1. 定义一个Point类来处理三维点points(x,y,z

2024-11-30 15:22:13
推荐回答(3个)
回答1:

编写程序:
1. 定义一个Point类来处理三维点points(x,y,z).该类有一默认的constructor,一copy constructor, 一negate()成员函数将point的x,y和z值各乘-1, 一norm()成员函数返回该点到原点(0,0,0)的距离,一个print()成员函数显示x,y,和z的值。

答:#include
#include
class Point
{ public:
Point(float x=0, float y=0, float z=0): x_(x), y_(y), z_(z) { }
Point(const Point& p) : x_(p.x_), y_(p.y_), z_(p.z_) { }
void negate() { x_ *= -1; y_ *= -1; z_ *= -1; }
double norm() { return sqrt(x_*x_ + y_*y_ + z_*z_); }
void print()
{ cout << '(' << x_ << "," << y_ << "," << z_ << ")";
}
private:
float x_, y_, z_;
};

void main()
{ Point p(12,-3,4);
cout << "p = ";
p.print();
cout << ", p.norm() = " << p.norm() << endl;
p.negate();
cout << "p = ";
p.print();
cout << ", p.norm() = " << p.norm() << endl;
}

2.定义一个Person类,它的每个对象表示一个人。数据成员必须包含姓名、出生年份、死亡年份,一个默认的构造函数,一析构函数,读取数据的成员函数,一个print()成员函数显示所有数据。

答:#include
class Person
{ public:
Person(char* =0, int =0, int =0);
~Person() { delete [] name_; }
char* name() { return name_; }
int born() { return yob_; }
int died() { return yod_; }
void print();
private:
int len_;
char* name_;
int yob_, yod_;
};

void main()
{ Person cb("Charles Babbage",1792,1871);
cb.print();
}

Person::Person(char* name, int yob, int yod)
: len_(strlen(name)),
name_(new char[len_+1]),
yob_(yob),
yod_(yod)
{ memcpy(name_, name, len_+1);
}

void Person::print()
{ cout << "\tName: " << name_ << endl;
if (yob_) cout << "\tBorn: " << yob_ << endl;
if (yod_) cout << "\tDied: " << yod_ << endl;
}

回答2:

3. #include
#define PI 3.1415926535898
class Shape
{
public:
Shape(){}
};
class Rectangle:public Shape
{
private:
double length,width;
public:
Rectangle(double a,double b):Shape(){length=a;width=b;}
double get_length(){return length;}
double get_width(){return width;}
double GetArea(){return get_length()*get_width();}
};
class Circle:public Shape
{
private:
double radius;
public:
Circle(double c):Shape(){radius=c;}
double get_radius(){return radius;}
double GetArea(){return PI*get_radius()*get_radius();}
};
void main()
{
Rectangle cf(7,8);
Circle yx(6);
cout<<"The Rectangle's area is: "< cout<<"The Circle's area is: "<}
4.#include
const double PI=3.14159;
class Shapes
{
protected:
int x,y;
public:
void setvalue(int xx,int yy=0){x=xx;y=yy;}
virtual void GetArea()=0;
virtual void GetPerim()=0;
};
class Rectangle:public Shapes
{
public:
void GetArea(){cout<<"The area of rectangle is:"<void GetPerim(){cout<<"The perim of rectangle is;"<<2*(x+y)<};
class Circle:public Shapes
{
public:
void GetArea(){cout<<"The area of circle is:"<void GetPerim(){cout<<"The perim of circle is:"<<2*PI*x<};
void main()
{
Shapes *ptr[2];
Rectangle rect1;
Circle cir1;
ptr[0]=&rect1;
ptr[0]->setvalue(5,8);ptr[0]->GetArea();ptr[0]->GetPerim();
ptr[1]=&cir1;
ptr[1]->setvalue(10);ptr[1]->GetArea();ptr[1]->GetPerim();
}

回答3:

a