繁体   English   中英

如何只为一个特定的函数和类声明好友函数?

[英]How can friend function be declared for only one particular function and class?

我的代码有什么问题?

我尝试在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声明中)。 那必须意味着在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);
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM