首页 > 解决方案 > 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;
  }

如果其中一个类声明与另一个类的友谊,它会被实现为普通方法吗?或者它是否也需要作为一个通用功能来实现?

标签: c++

解决方案


这个例子中只有一个类。

这个例子中的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


推荐阅读