简体   繁体   English

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

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

What's wrong with my code? 我的代码有什么问题?

I tried to compile the code below in the GNU G++ environment and I get these errors: 我尝试在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;
}

A member function must be first declared in its class (not in a friend declaration). 成员函数必须首先在其类中声明(而不是在friend声明中)。 That must mean that prior to the friend declaration, you should have the class of it defined - a mere forward declaration does not suffice. 那必须意味着在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.

相关问题 在B类中声明为朋友的A类成员模板函数无法访问A类的私有成员(仅限Clang) - Class A member template function declared as friend in class B can't access private members of class A (Clang only) 在类范围之外声明的函数,但不是朋友。 这是如何运作的? - Function declared outside class scope but not friend. How does this work? 类的朋友功能,只能由特定类使用 - A friend function of a class that can only be used by a specific class 类的Friend Function产生错误:“未声明&#39;___&#39;成员函数” - Friend Function of Class produces error: “no '___' member function declared” 如何使用好友功能或好友类? - How to use friend function or friend class? 从具有正向声明的类中向具有朋友功能的已声明单身类转发 - Forward declared singleton class with a friend function from the class with the forward declaration 如何定义在两个类之外的模板类内部的非模板类中声明的友元函数? - How to define a friend function declared in a non template class internal to a template class outside of both classes? 一班朋友的功能 - Function of one class friend of another class 如何给朋友模板类功能 - How to friend template class function 我如何在基类中为派生类函数做朋友? - How can I friend a derived class function in the base class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM