23-5 依赖
迄今为止,我们探讨了三种关系类型:组合、聚合和关联。最简单的依赖关系留到了最后。
在日常对话中,我们用“依赖”一词表示某个对象在完成特定任务时需要另一个对象的支持。例如,若你脚部骨折,就需要依靠拐杖行走(但其他情况下则不需要)。花朵依赖蜜蜂授粉才能结果或繁殖(但仅限于此)。
当某个对象调用另一个对象的功能以完成特定任务时,便形成了依赖关系。这种关系比关联关系更弱,但被依赖对象的任何变更仍可能导致调用方(依赖方)的功能失效。依赖关系始终是单向的。
你已多次见过的典型依赖关系实例是 std::ostream。使用 std::ostream 的类仅为实现控制台输出功能而依赖它,除此之外并无其他关联。
例如:
#include <iostream>
class Point
{
private:
double m_x{};
double m_y{};
double m_z{};
public:
Point(double x=0.0, double y=0.0, double z=0.0): m_x{x}, m_y{y}, m_z{z}
{
}
friend std::ostream& operator<< (std::ostream& out, const Point& point); // Point has a dependency on std::ostream here
};
std::ostream& operator<< (std::ostream& out, const Point& point)
{
// Since operator<< is a friend of the Point class, we can access Point's members directly.
out << "Point(" << point.m_x << ", " << point.m_y << ", " << point.m_z << ')';
return out;
}
int main()
{
Point point1 { 2.0, 3.0, 4.0 };
std::cout << point1; // the program has a dependency on std::cout here
return 0;
}
在上面的代码中,Point 类本身与 std::ostream 没有直接关联,但它依赖于 std::ostream,因为 operator<< 操作符使用 std::ostream 将 Point 对象打印到控制台。

C++中的依赖关系与关联关系
人们通常容易混淆依赖关系与关联关系的区别。
在C++中,关联关系是指一个类通过成员变量直接或间接“链接”关联类的关系。例如,Doctor类拥有指向其Patients的指针数组作为成员变量。你总能询问医生其患者是谁。Driver类将驾驶员对象拥有的Car对象ID作为整型成员存储。Driver始终知晓与其关联的Car对象。
依赖关系通常不以成员形式存在。被依赖的对象通常按需实例化(如打开文件写入数据),或作为参数传递给函数(如上文重载的<<运算符中的std::ostream)。
幽默插曲
依赖项(由我们的朋友xkcd提供):

当然,你我都清楚这其实是一种反射性联想!

浙公网安备 33010602011771号