c++ - c ++ - 使用方法或通用函数两个文件的友谊实现
问题描述
当我有两个 .h 类时,您必须将方法实现到两个相应的 cpps 类中。因为它发生在同一个文件中,当我有:
class test
{
int a;
int b;
public:
friend int sum ();
};
int sum ()
{
test t;
t.a = 1;
t.b = 2;
return t.a+t.b;
}
如果其中一个类声明与另一个类的友谊,它会被实现为普通方法吗?或者它是否也需要作为一个通用功能来实现?
解决方案
这个例子中只有一个类。
这个例子中的friend关键字只是声明sum
允许外部函数(在这种情况下)访问与其有友谊的类的私有属性/方法。这是一个正常的功能,而不是一种方法,因此是这样的:test::sum()
或者test t; t.sum()
是不可能的。
如果你想使用另一个类从这个类访问私有属性/方法,它的工作方式如下:
#include <iostream>
class Test2;
class Test1 {
int a;
int b;
public:
Test1(int a, int b) : a(a), b(b) {}
int sum(const Test2& t) const;
};
class Test2 {
int c;
public:
Test2(int c) : c(c) {}
friend int Test1::sum(const Test2& t) const;
};
int Test1::sum(const Test2& t) const { return a + b + t.c; }
int main()
{
Test1 t1(2, 4);
Test2 t2(3);
std::cout << t1.sum(t2) << std::endl;
return 0;
}
有关关键字的更多具体信息,friend
请查看此处:
https ://en.cppreference.com/w/cpp/language/friend
推荐阅读
- python - 如何基于多个列将一个数据帧中的列添加到另一个数据帧
- sql - oracle 中的每周最大计数记录
- angular - 在 Angular 中的每个 API 之上调用一个通用 API
- nginx - Nginx 负载均衡器作为基于 geoip 的流量路由器
- python - 将 csv 数据保存到字典中
- php - 使用 preg_replace 替换里面的字符串
- python - pip install pandas 不工作,即使我似乎有 pip
- html - 下拉菜单怪癖...何时由 CLASS 与 ID 控制
- ios - 一段时间后,静默推送通知不会触发“didReceiveRemoteNotification”吗?
- java - 我想用实时数据库中保存的日期发出通知