- 设计二维空间的点类Dot,并将求两点之间距离的函数声明为点类Dot的友元函数。
成员变量:
double x,y;
成员函数:
Dot(double xx=0,double yy=0);//构造函数
~Dot();//析构函数
void setX(double xx);//设置点的x坐标
void setY(double yy);//设置点的y坐标
double getX();//获取点的x坐标
double getY();//获取点的y坐标
void print(); //输出点的坐标
友元函数:
friend double distance(Dot d1,Dot d2);2. 求二维空间两点之间的距离: - 求二维空间两点之间的距离:
double distance(Dot d1,Dot d2); - 设计main函数进行测试,并求点A(1, 2)、B(3, 5)之间的距离。
#pragma once
class Dot
{
public:
Dot(double, double);//构造函数
~Dot() {};//析构函数
void setX(double xx);//设置点的x坐标
void setY(double yy);//设置点的y坐标
double getX();//获取点的x坐标
double getY();//获取点的y坐标
void print(); //输出点的坐标
friend double distance(Dot d1, Dot d2);
private:
double x, y;
};
#include "Dot.h"
#include<cmath>
#include<iostream>
using namespace std;
void Dot::setX(double xx) {
x = xx;
}
void Dot::setY(double yy) {
y = yy;
}
double Dot::getX() {
return x;
}
double Dot::getY() {
return y;
}
void Dot::print() {
cout << "(" << x << "," << y << ")" << endl;
}
Dot::Dot(double xx, double yy) {
x = xx;
y = yy;
}
double distance(Dot a, Dot b) {
double distance = 0;
distance = sqrt(pow(b.x - a.x, 2) + pow(b.y - a.y, 2));
return distance;
}
#include<iostream>
#include"Dot.h"
using namespace std;
int main() {
Dot a(1, 2); Dot b(3, 5); Dot c(0, 0);
cout << distance(a, b) << endl;
system("pause");
return 0;
}
复数类+复数的加减乘运算(友元函数)
#pragma once
class complex
{
public:
complex(void);
complex(double, double);
friend complex add(complex a,complex b);
void norm();
friend complex aqq(complex a,complex b);
void print();
void set(double, double);
complex(complex &c);
private:
double i, j;
};
#include "complex.h"
#include<math.h>
#include<iostream>
using namespace std;
complex::complex(void)
{
i = 0;
j = 0;
}
complex::complex(double i2, double j2) {
i = i2;
j = j2;
}
complex::complex(complex &b) {
i = b.i;
j = b.j;
}
void complex::norm() {
double sum;
sum = sqrt(i*i + j * j);
cout << "模为:" << sum << endl;
}
void complex::print() {
cout << i << "i" << j << "j" << endl;
}
void complex::set(double a, double b) {
i = a;
j = b;
}
complex add(complex a, complex b) {
complex y(a.i + b.i, a.j + b.j);
return y;
}
complex aqq(complex c, complex d) {
complex y(c.i - d.i, c.j - d.j);
return y;
}
#include<iostream>
using namespace std;
#include"complex.h"
int main() {
complex a(3, 4), b(6, 10);
complex c(a);
a.print();
a.norm();
a.print();
b.print();
a.norm();
a.print();
c = add(a,b);
c.print();
c = aqq(a,b);
c.print();
system("pause");
return 0;
}
1 条评论
感谢分享 赞一个