类中的构造函数


//---------a.h------------
#ifndef __A_H
#define __A_H

#include <iostream>

//namespace abc
//{
//	void myname();
//}

class PPoint
{
private:
	double x,y;
public:
	PPoint(double ix,double iy);
	double xOffset();
	double yOffset();
	double angle();
	double radius();
};

#endif

//---------a.cpp------------
#include "a.h"
#include <cmath>

//using namespace std;
//
//void abc::myname()
//{
//	std::cout<<"abc-myname"<<endl;
//}

PPoint::PPoint(double ix,double iy)
{
	x=ix;
	y=iy;
}

double PPoint::xOffset()
{
	return x;
}
double PPoint::yOffset()
{
	return y;
}
//直角坐标转化成极坐标
double PPoint::angle()
{
	return ((180.0/3.14159)*atan2(y,x));
}
double PPoint::radius()
{
	return (sqrt(x*x+y*y));
}

//---------main.cpp------------
#include <iostream>
#include <string>
#include "a.h"

using namespace std;

int main(int argc,char **argv)
{
	
	for(double x,y;cout<<"Enter x and y,to change an angle and a radius :"&& cin>>x>>y;)
	{
		PPoint p(x,y);
		std::cout<<"the angle is :"<<p.angle()<<"  the radius is :"<<p.radius()<<endl;
	}
	return 0;
}

Enter x and y,to change an angle and a radius :1 1
the angle is :45  the radius is :1.41421
Enter x and y,to change an angle and a radius :


使用构造函数来创建对象,使得对象初始化能够一次性解决。程序员完全可以在构造函数中严格检查对象的初值条件,本程序中的构造函数没有正确性校验,结果的正确性与否完全依赖于输入数据的合法性。


1


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值