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存储空间