繁体   English   中英

如何使一个文件的朋友与另一个文件的类成为非成员函数?

[英]How to make non-member function from one file friend with class in other file?

可以说我有一个文件

// Xh(第一个文件)

#include <iostream>
class X{
    int x;
public:
    X(int i);
    void print_me();
};

// X.cpp(第二个文件)

#include "X.h"
X::X(int i){x = i}

void X::print_me(){std::cout<< x << endl;}

// main.cpp(第三个文件)

#include "X.h"

void swap(int lhs, int rhs){
  // do the swap
}

class Y{
   X x_obj;
public: 
    friend void swap(Y& lhs, Y& rhs){
        swap(lhs.x_obj.x, rhs.x_obj.x);
    }

};
int main(){return 0;}

我的问题是:如何使main.cpp中的Y类成为X的朋友?

我正在考虑将类Y分解为.h和.cpp文件,并将Yh文件包括进Xh并从那里去。 除此之外还有其他办法吗? 我的意思是在代码的当前条件下,使Y成为X的朋友:

我在当前情况下遇到的错误是:

> In file included from main.cpp:1:0: X.h: In function 'void swap(Y&,
> Y&)': X.h:3:9: error: 'int X::x' is private
>      int x;
>          ^ main.cpp:12:24: error: within this context
>          swap(lhs.x_obj.x, rhs.x_obj.x);
>                         ^ In file included from main.cpp:1:0: X.h:3:9: error: 'int X::x' is private
>      int x;
>          ^ main.cpp:12:37: error: within this context
>          swap(lhs.x_obj.x, rhs.x_obj.x);

我的问题是:如何使main.cpp中的Y类成为X的朋友?

使Y成为X的朋友将无法解决此问题。 您需要让类X的函数swap()朋友,因为它试图访问X的私有成员。

class Y; // forward declaration to avoid circular dependencies
class X{
    friend void swap(Y& lhs, Y& rhs);
    ...
};

注意,应该使用前向声明以避免将Yh包含到Xh ,这会导致循环依赖性问题

暂无
暂无

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

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