Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/149.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 实现好友功能_C++_Friend Function - Fatal编程技术网

C++ 实现好友功能

C++ 实现好友功能,c++,friend-function,C++,Friend Function,我有两个班湿度和温度。它们有友元函数,这在它们的头文件中声明: friend void PrintWeather(const Temperature &cTemperature, const Humidity &cHumidity); 在哪里方便实现该功能(Temperature.cpp,湿度.cpp,或另一个文件.cpp)?因为函数PrintWeather没有逻辑耦合 对于一个类而不是另一个类,我将在一个单独的文件中实现它,可能是weather.cpp。我使用小写字母表示该文

我有两个班
湿度
温度
。它们有友元函数,这在它们的头文件中声明:

friend
void PrintWeather(const Temperature &cTemperature, const Humidity &cHumidity);

在哪里方便实现该功能(
Temperature.cpp
湿度.cpp
,或
另一个文件.cpp
)?

因为函数
PrintWeather
没有逻辑耦合 对于一个类而不是另一个类,我将在一个单独的文件中实现它,可能是
weather.cpp
。我使用小写字母表示该文件不包含类
Weather
,而是包含与天气相关的函数

另外,我强烈建议对所有这些应用程序使用类似
weather
的名称空间


如果不知道你展示的更多,我会质疑你的设计。为什么
PrintWeather
需要访问
温度
湿度
的内部?它应该只使用这两个函数的公共接口。

PrintWeather函数的名称意味着它谈论的是一种叫做
天气的东西。因此,也许您应该将
天气
(或
天气预报
)设置为一个单独的类,该类收集天气的所有组成部分:

class Weather
{
  private: 
    Temperature temperature;
    Humidity humidity;

  public:
    void Print();
    // or: void Print(std::ostream& out) const;
}
请注意,函数的名称现在可以是
Print
——它所打印的内容在它所在的类中已经很清楚了,而不是在

weatherForecast.PrintWeather();
你得写作

weatherForecast.Print();

现在,如果您的任务需要,您可以授予
天气
朋友
访问
温度
湿度
。然而,我想指出的是,在实际设计中,您希望尽可能避免
朋友
s(俗话说:“您不想让您的朋友触碰您的私处”-只需提供
温度
湿度
,并提供适当的
公共
界面即可).

这只是朋友函数教程中的一个示例。我一直对在这种情况下使用什么方法感兴趣。或者将文件命名为
output\u functions.cpp
。或者更好的是,创建一个
WeatherForecast
类,其中包含一个
温度
湿度
对象作为字段,该类具有
打印
功能。