朋友成员函数可以在单独的文件中使用吗? 我正在阅读C++底漆,我被困在
7.3.4。重温友谊让会员成为朋友 练习7.32:定义自己的屏幕和窗口管理器版本,其中 clear是Window_mgr的成员,也是Screen的朋友 我在一个文件中找到了几个已解决的练习:朋友成员函数可以在单独的文件中使用吗? 我正在阅读C++底漆,我被困在,c++,makefile,friend,friend-function,C++,Makefile,Friend,Friend Function,7.3.4。重温友谊让会员成为朋友 练习7.32:定义自己的屏幕和窗口管理器版本,其中 clear是Window_mgr的成员,也是Screen的朋友 我在一个文件中找到了几个已解决的练习: #include <iostream> #include <string> #include <vector> using std::cin; using std::cout; using std::string; using std::vector; using st
#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;
}
#包括
#包括
#包括
使用std::cin;
使用std::cout;
使用std::string;
使用std::vector;
使用std::ostream;
类屏幕;
班级窗口经理{
公众:
使用ScreenIndex=vector::size\u type;
空白清除(屏幕索引i);
私人:
矢量屏幕;
};
类屏幕{
朋友无效窗口管理器::清除(屏幕索引);
公众:
类型定义字符串::大小\类型位置;
屏幕(位置ht,位置wd,字符c):高度(ht),宽度(wd),内容(ht*wd,c){}
私人:
pos游标=0;
位置高度=0,宽度=0;
字符串内容;
};
无效窗口管理器::清除(屏幕索引i){
屏幕&s=屏幕[i];
s、 内容=字符串(s.height*s.width');
}
int main(){
窗口管理器变量;
返回0;
}
我试图在5个单独的文件中解决它,如main.cpp、Window_mgr.h、Window_mgr.cpp、Screen.h和Screen.cpp;还是没有运气。
我在stackoverflow中研究过这个练习,我发现了很多,但是关于在单独的文件中编译它的任何东西,所以我想
朋友成员函数必须在同一文件中编译
如果不是
如何在它自己的文件中分离每个类,分离实现和接口
- main.cpp
- Screen.h/Screen.cpp
- 窗口管理器.h/窗口管理器.cpp
makefile
这可能吗?
谢谢 我认为,问题是循环引用,如果你用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
\ifndef\uu SRCEEN__
#定义__
#包括
#包括“窗口经理h”
使用名称空间std;
类屏幕{
好友无效窗口\ u管理器::清除(屏幕索引);//需要窗口\ u管理器定义
公众:
类型定义字符串::大小\类型位置;
屏幕(位置ht,位置wd,字符c):高度(ht),宽度(wd),内容(ht*wd,c){}
私人:
pos游标=0;
位置高度=0,宽度=0;
字符串内容;
};
#恩迪夫
您的窗口经理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
\ifndef\uuu窗口管理器__
#定义窗口管理器__
#包括
#包括
#包括“Screen.h”
使用名称空间std;
类屏幕;
班级窗口经理{
公众:
使用ScreenIndex=vector::size\u type;//需要屏幕定义
空隙清除(尺寸i);
私人:
向量屏幕;//需要屏幕定义
};
#恩迪夫
它们需要得到彼此的定义,您可以使用前向声明在单个文件中解决,但对于这种情况,这似乎不是一个好的解决方案:(朋友成员函数必须在同一个文件中编译?否。