| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 522 人关注过本帖
标题:類的派生該怎么用??
只看楼主 加入收藏
iwar
Rank: 1
等 级:新手上路
帖 子:7
专家分:0
注 册:2007-4-16
收藏
 问题点数:0 回复次数:2 
類的派生該怎么用??

#include <iostream.h>

#include <math.h> //for sqrt()

class C2D

{

protected:

double x, y; //x and y coordinates

public:

C2D() { x = y = 0.0; } //default constructor

C2D(double i, double j):x(i), y(j) { }

void setX(double newX) { x = newX; }

void setY(double newY) { y = newY; }

double getX() const { return x; }

double getY() const { return y; }

double getDistance(C2D point) const; // get distance of 2D points

};

// calculate the distance of two 2D points

double C2D::getDistance(C2D point) const

{

double dx, dy;

double distance;

dx = x – point.getX();

dy = y – point.getY();

distance = sqrt(dx * dx + dy * dy);

return distance;

}

class C3D:public C2D

{

private:

double z;

public:

C3D():C2D();

C3D(double i, double j, double k);

void setZ(double newZ);

double getZ();

double getDistance(C3D point) const; //get distance for two 3D points

};

該怎麽延伸到三維的啊!!!!
搜索更多相关主题的帖子: 派生 
2007-05-26 14:34
weishj
Rank: 1
等 级:新手上路
威 望:2
帖 子:141
专家分:0
注 册:2007-4-22
收藏
得分:0 

#include <iostream>
#include <cmath>
using namespace std;
class C2D
{
protected:
double x, y;
public:
C2D() { x = y = 0.0; }
C2D(double i, double j):x(i), y(j) { }
void setX(double newX) { x = newX; }
void setY(double newY) { y = newY; }
double getX() const { return x; }
double getY() const { return y; }
double getDistance(const C2D point1) const;
};
double C2D::getDistance(const C2D point) const
{
double dx,dy;
double distance;
dx=x-point.getX();
dy=y-point.getY();
distance=sqrt(dx * dx + dy * dy);
return distance;
}
class C3D:public C2D
{
private:
double z;
public:
C3D():C2D(0.0,0.0),z(0.0){}
C3D(double i, double j, double k):C2D(i,j),z(k){}
void setZ(double newZ){z=newZ;}
double getZ(){return z;}
double getDistance(C3D point) const;
};
double C3D::getDistance(C3D point) const
{
double dx, dy,dz;
dx=x-point.getX();
dy=y-point.getY();
dz=z-point.getZ();
return sqrt(dx*dx+dy*dy+dz*dz);
}
void main()
{
C2D c2d;
C3D c3d;
C2D a;
C3D b;
a.setX(1.0);
a.setY(2.0);
b.setX(1.0);
b.setY(2.0);
b.setZ(3.0);
cout<<c2d.getDistance(a)<<endl;//a与c2d两点的距离
cout<<c3d.getDistance(b)<<endl;//b与c3d两点的距离
}


If you shed tears when you miss the sun, you also miss the stars.
2007-05-27 18:02
iwar
Rank: 1
等 级:新手上路
帖 子:7
专家分:0
注 册:2007-4-16
收藏
得分:0 
thx
2007-05-28 18:49
快速回复:類的派生該怎么用??
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.083695 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved