C++ 7 类与对象 友元函数2

C++ 7 类与对象 友元函数2

题目 1

编程序,求空间中(不是平面中)二点间距离,通过友元函数访问私有成员

程序:

#include<iostream>
#include<math.h>
using namespace std;
class Point
{
	double x, y, z;
public:
	Point(double a = 0, double b = 0, double c = 0)
	{
		x = a;
		y = b;
		z = c;
	}
	~Point()
	{}
	friend double d(Point &p1, Point &p2);

};
double d(Point &p1, Point &p2)
{
	return sqrt((p1.x - p2.x)*(p1.x - p2.x) + (p1.y - p2.y)*(p1.y - p2.y) + (p1.z - p2.z)*(p1.z - p2.z));
}

void main()
{
	Point p1, p2(1, 1, 1);
	cout << d(p1, p2) << endl;
}

运行结果
在这里插入图片描述

题目 2

  • 定义一个复数类,测试友元函数作用
  • 在这里插入图片描述
    在这里插入图片描述
    要求:(1)补充完善上述程序,得到如下结果截图;

在这里插入图片描述
1)程序:

:#include<iostream>
using namespace std;
class complex
{
	double real, image;
public:
	complex(double rr = 0, double ii = 0)
	{
		real = rr; image = ii; cout << "构造函数被调用.." << endl;
	}
	complex(complex &c)
	{
		real = c.real; image = c.image; cout << "拷贝构造函数被调用.." << endl;
	}
	~complex()
	{
		cout << "析构函数被调用..." << endl;
	}
	friend void print(complex &);
};
void print(complex &c)
{
	if (c.image < 0)
		cout << c.real << c.image << 'i';
	else if (c.image>0)
		cout << c.real << '+' << c.image << 'i';
	else
		cout << c.real;
	cout << '\n';
}
void main()
{
	complex c1(1, 2), c2(3, -4), c3(c2);
	print(c1);
	print(c2);
	print(c3);
}

在这里插入图片描述
2)解释截图中的每一行
定义变量c1,调用构造函数
定义变量c2,调用构造函数
定义变量c3的值等于c2,调用拷贝构造函数
输出c1的值
输出c2的值
输出c3的值
撤销c3存储空间
撤销c2存储空间
撤销c1存储空间

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值