【问题标题】:A Friend member Function can be used in separated files?Friend 成员函数可以在单独的文件中使用吗?
【发布时间】:2018-06-30 18:05:43
【问题描述】:

我正在阅读 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 中编译

这可能吗? 谢谢!

【问题讨论】:

  • Friend成员函数必须编译在同一个文件中?不。

标签: c++ makefile friend friend-function


【解决方案1】:

我认为,问题是循环引用,如果你用 5 个单独的文件解决它,Screen.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

你的 window_mgr.h

#ifndef __WINDOW_MGR__
#define __WINDOW_MGR__
#include <string>
#include <vector>
#include "Screen.h"
using namespace std;
class Screen;
class Window_mgr{
public:
   using ScreenIndex = vector<Screen>::size_type;// need Screen defination
   void clear(size_t i);
private:
   vector<Screen> screens;// need Screen defination
};
#endif

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-18
    • 2019-10-18
    • 2011-06-20
    • 2013-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多