朋友成员函数可以在单独的文件中使用吗?

时间:2018-06-30 18:05:43

标签: c++ makefile friend friend-function

我正在阅读C ++ Primer,却被困在

7.3.4。重新建立友谊使成员职能成为朋友

  

练习7.32:定义您自己的Screen和Window_mgr版本,其中   clear是Window_mgr的成员和Screen的朋友

我发现了几个已解决的练习,但仅存在一个文件中:

#include <iostream>
#include <string>
#include <vector>

using std::cin;
using std::cout;
using std::string;
using std::vector;
using std::ostream;

class Screen;

class Window_mgr{
public:
    using ScreenIndex = vector<Screen>::size_type;
    void clear(ScreenIndex i);
private:
    vector<Screen> screens;
};

class Screen{
    friend void Window_mgr::clear(ScreenIndex);
public:
    typedef string::size_type   pos;
    Screen(pos ht, pos wd, char c) : height(ht), width(wd), contents(ht * wd, c) {}

private:
    pos cursor = 0;
    pos height = 0, width = 0;
    string contents;
};

void Window_mgr::clear(ScreenIndex i){
    Screen &s = screens[i];
    s.contents = string(s.height * s.width, ' ');
}

int main(){
    Window_mgr var;
    return 0;
}

我试图在5个单独的文件中解决它,分别是main.cpp,Window_mgr.h,Window_mgr.cpp,Screen.h和Screen.cpp;仍然没有运气。 我在stackoverflow中研究了此练习,发现了很多东西,但是有关在单独的文件中进行编译的任何内容,所以我在想...

  

朋友成员函数必须在同一文件中编译吗?

如果不是

  

如何将每个类分隔在自己的文件中,以分隔实现和接口?

     
    
        
  • main.cpp
  •     
  • Screen.h / Screen.cpp
  •     
  • Window_mgr.h / Window_mgr.cpp
  •     
  

  

可选:这5个文件必须以什么顺序(如何编译)在makefile

这可能吗? 谢谢!

1 个答案:

答案 0 :(得分:0)

我认为,问题是循环引用,如果您通过5个单独的文件Screen.h解决它,

df.loc[ ( "x", "y" ), :] = 1,2
print (df)
       c1  c2
i1 i2        
x  y    1   2

您的window_mgr.h

#ifndef __SRCEEN__
#define __SRCEEN__
#include <string>
#include "window_mgr.h"
using namespace std;
class Screen{
    friend void Window_mgr::clear(ScreenIndex);// need Window_mgr defination
public:
    typedef string::size_type pos;
    Screen(pos ht, pos wd, char c) : height(ht), width(wd), contents(ht * wd, c) {}

private:
    pos cursor = 0;
    pos height = 0, width = 0;
    string contents;
};
#endif

他们需要获取彼此的定义,可以使用前向声明在单个文件中解决它,但是对于这种情况似乎不是一个好的解决方案:(

相关问题