如何只为一个特定的函数和类声明friend函数? [英] How can friend function be declared for only one particular function and class?

查看:255
本文介绍了如何只为一个特定的函数和类声明friend函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码有什么问题?

我试图在GNU G ++环境中编译下面的代码,我得到这些错误:

I tried to compile the code below in the GNU G++ environment and I get these errors:


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


推荐答案

在其类中声明(不在朋友声明中)。这必须意味着在朋友宣告之前,你应该定义它的类 - 只是向前的声明是不够的。

A member function must be first declared in its class (not in a friend declaration). That must mean that prior to the friend declaration, you should have the class of it defined - a mere forward declaration does not suffice.

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

这篇关于如何只为一个特定的函数和类声明friend函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆