【问题标题】:How can friend function be declared for only one particular function and class?如何只为一个特定的函数和类声明友元函数?
【发布时间】:2009-12-27 16:00:25
【问题描述】:

我的代码有什么问题?

我尝试在 GNU G++ 环境中编译以下代码,但出现以下错误:

朋友2.cpp:30:错误:不完整类型“结构二”的使用无效 friend2.cpp:5:错误:“结构二”的前向声明 friend2.cpp:在成员函数“int two::accessboth(one)”中: 朋友2.cpp:24:错误:“int one::data1”是私有的 friend2.cpp:55:错误:在此上下文中
#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;
}

【问题讨论】:

    标签: c++ friend-function


    【解决方案1】:

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

    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);
     }
    

    【讨论】:

      猜你喜欢
      • 2019-04-20
      • 1970-01-01
      • 1970-01-01
      • 2016-02-24
      • 2020-08-07
      • 1970-01-01
      • 2013-03-31
      • 1970-01-01
      相关资源
      最近更新 更多