c++ - 如何只为一个特定的函数和类声明友元函数?

标签 c++ friend-function

我的代码有什么问题?

我试图在 GNU G++ 环境中编译下面的代码,但出现了这些错误:

friend2.cpp:30: error: invalid use of incomplete type ‘struct two’
friend2.cpp:5: error: forward declaration of ‘struct two’
friend2.cpp: In member function ‘int two::accessboth(one)’:
friend2.cpp:24: error: ‘int one::data1’ is private
friend2.cpp:55: error: within this context
#include <iostream>
using namespace std;

class two;

class one
{
    private:
        int data1;
    public:
        one()
        {
            data1 = 100;
        }

        friend int two::accessboth(one a);
};

class two
{
    private:
        int data2;

    public:
        two()
        {
            data2 = 200;
        }

        int accessboth(one a);
};

int two::accessboth(one a)
{
    return (a.data1 + (*this).data2);
}

int main()
{
    one a;
    two b;
    cout << b.accessboth(a);
    return 0;
}

最佳答案

成员函数必须首先在其类中声明(而不是在友元声明中)。这一定意味着在 friend 声明之前,你应该定义它的类——仅仅一个前向声明是不够的。

class one;

class two
 {
    private:
  int data2;
    public:
  two()
  {
    data2 = 200;
  }
 // this goes fine, because the function is not yet defined. 
 int accessboth(one a);
 };

class one
 {
     private:
  int data1;
    public:
  one()
  {
    data1 = 100;
  }
    friend int two::accessboth(one a);
 };

 // don't forget "inline" if the definition is in a header. 
 inline int two::accessboth(one a) {
  return (a.data1 + (*this).data2);
 }

关于c++ - 如何只为一个特定的函数和类声明友元函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1966255/

相关文章:

c++ - 共享库中的静态全局字段——它们去哪儿了?

c++ - 推荐内存占用较小的快速 C++ UI 库

c++ - 如果未定义的 C++ 行为符合 C 定义的行为会发生什么?

c++ - 使用友元函数迭代另一个类的私有(private)成员

c++ - 为什么在丢弃指向该对象的指针的常量之后写入一个非常量对象而不是 UB?

c++ - 检测手机或相机的插入

c++ - 在重载 I/O 运算符中重载增量运算符时出错

c++ - 如何在C++中为友元函数提供保护

c++ - 如何解决 "class must be used when declaring a friend"错误?